qapi: Rewrite parsing of doc comment section symbols and tags
[qemu/armbru.git] / net / slirp.c
blobc33b3e02e70ab53c676ed64f5898d2a92e53cae1
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-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.
25 #include "qemu/osdep.h"
26 #include "qemu/log.h"
27 #include "net/slirp.h"
30 #if defined(CONFIG_SMBD_COMMAND)
31 #include <pwd.h>
32 #include <sys/wait.h>
33 #endif
34 #include "net/eth.h"
35 #include "net/net.h"
36 #include "clients.h"
37 #include "hub.h"
38 #include "monitor/monitor.h"
39 #include "qemu/error-report.h"
40 #include "qemu/sockets.h"
41 #include <libslirp.h>
42 #include "chardev/char-fe.h"
43 #include "sysemu/sysemu.h"
44 #include "qemu/cutils.h"
45 #include "qapi/error.h"
46 #include "qapi/qmp/qdict.h"
47 #include "util.h"
48 #include "migration/register.h"
49 #include "migration/qemu-file-types.h"
51 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
53 const char *p, *p1;
54 int len;
55 p = *pp;
56 p1 = strchr(p, sep);
57 if (!p1)
58 return -1;
59 len = p1 - p;
60 p1++;
61 if (buf_size > 0) {
62 if (len > buf_size - 1)
63 len = buf_size - 1;
64 memcpy(buf, p, len);
65 buf[len] = '\0';
67 *pp = p1;
68 return 0;
71 /* slirp network adapter */
73 #define SLIRP_CFG_HOSTFWD 1
75 struct slirp_config_str {
76 struct slirp_config_str *next;
77 int flags;
78 char str[1024];
81 struct GuestFwd {
82 CharBackend hd;
83 struct in_addr server;
84 int port;
85 Slirp *slirp;
88 typedef struct SlirpState {
89 NetClientState nc;
90 QTAILQ_ENTRY(SlirpState) entry;
91 Slirp *slirp;
92 Notifier poll_notifier;
93 Notifier exit_notifier;
94 #if defined(CONFIG_SMBD_COMMAND)
95 gchar *smb_dir;
96 #endif
97 GSList *fwd;
98 } SlirpState;
100 static struct slirp_config_str *slirp_configs;
101 static QTAILQ_HEAD(, SlirpState) slirp_stacks =
102 QTAILQ_HEAD_INITIALIZER(slirp_stacks);
104 static int slirp_hostfwd(SlirpState *s, const char *redir_str, Error **errp);
105 static int slirp_guestfwd(SlirpState *s, const char *config_str, Error **errp);
107 #if defined(CONFIG_SMBD_COMMAND)
108 static int slirp_smb(SlirpState *s, const char *exported_dir,
109 struct in_addr vserver_addr, Error **errp);
110 static void slirp_smb_cleanup(SlirpState *s);
111 #else
112 static inline void slirp_smb_cleanup(SlirpState *s) { }
113 #endif
115 static ssize_t net_slirp_send_packet(const void *pkt, size_t pkt_len,
116 void *opaque)
118 SlirpState *s = opaque;
119 uint8_t min_pkt[ETH_ZLEN];
120 size_t min_pktsz = sizeof(min_pkt);
122 if (net_peer_needs_padding(&s->nc)) {
123 if (eth_pad_short_frame(min_pkt, &min_pktsz, pkt, pkt_len)) {
124 pkt = min_pkt;
125 pkt_len = min_pktsz;
129 return qemu_send_packet(&s->nc, pkt, pkt_len);
132 static ssize_t net_slirp_receive(NetClientState *nc, const uint8_t *buf, size_t size)
134 SlirpState *s = DO_UPCAST(SlirpState, nc, nc);
136 slirp_input(s->slirp, buf, size);
138 return size;
141 static void slirp_smb_exit(Notifier *n, void *data)
143 SlirpState *s = container_of(n, SlirpState, exit_notifier);
144 slirp_smb_cleanup(s);
147 static void slirp_free_fwd(gpointer data)
149 struct GuestFwd *fwd = data;
151 qemu_chr_fe_deinit(&fwd->hd, true);
152 g_free(data);
155 static void net_slirp_cleanup(NetClientState *nc)
157 SlirpState *s = DO_UPCAST(SlirpState, nc, nc);
159 g_slist_free_full(s->fwd, slirp_free_fwd);
160 main_loop_poll_remove_notifier(&s->poll_notifier);
161 unregister_savevm(NULL, "slirp", s->slirp);
162 slirp_cleanup(s->slirp);
163 if (s->exit_notifier.notify) {
164 qemu_remove_exit_notifier(&s->exit_notifier);
166 slirp_smb_cleanup(s);
167 QTAILQ_REMOVE(&slirp_stacks, s, entry);
170 static NetClientInfo net_slirp_info = {
171 .type = NET_CLIENT_DRIVER_USER,
172 .size = sizeof(SlirpState),
173 .receive = net_slirp_receive,
174 .cleanup = net_slirp_cleanup,
177 static void net_slirp_guest_error(const char *msg, void *opaque)
179 qemu_log_mask(LOG_GUEST_ERROR, "%s", msg);
182 static int64_t net_slirp_clock_get_ns(void *opaque)
184 return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
187 typedef struct SlirpTimer SlirpTimer;
188 struct SlirpTimer {
189 QEMUTimer timer;
190 #if SLIRP_CHECK_VERSION(4,7,0)
191 Slirp *slirp;
192 SlirpTimerId id;
193 void *cb_opaque;
194 #endif
197 #if SLIRP_CHECK_VERSION(4,7,0)
198 static void net_slirp_init_completed(Slirp *slirp, void *opaque)
200 SlirpState *s = opaque;
201 s->slirp = slirp;
204 static void net_slirp_timer_cb(void *opaque)
206 SlirpTimer *t = opaque;
207 slirp_handle_timer(t->slirp, t->id, t->cb_opaque);
210 static void *net_slirp_timer_new_opaque(SlirpTimerId id,
211 void *cb_opaque, void *opaque)
213 SlirpState *s = opaque;
214 SlirpTimer *t = g_new(SlirpTimer, 1);
215 t->slirp = s->slirp;
216 t->id = id;
217 t->cb_opaque = cb_opaque;
218 timer_init_full(&t->timer, NULL, QEMU_CLOCK_VIRTUAL,
219 SCALE_MS, QEMU_TIMER_ATTR_EXTERNAL,
220 net_slirp_timer_cb, t);
221 return t;
223 #else
224 static void *net_slirp_timer_new(SlirpTimerCb cb,
225 void *cb_opaque, void *opaque)
227 SlirpTimer *t = g_new(SlirpTimer, 1);
228 timer_init_full(&t->timer, NULL, QEMU_CLOCK_VIRTUAL,
229 SCALE_MS, QEMU_TIMER_ATTR_EXTERNAL,
230 cb, cb_opaque);
231 return t;
233 #endif
235 static void net_slirp_timer_free(void *timer, void *opaque)
237 SlirpTimer *t = timer;
238 timer_del(&t->timer);
239 g_free(t);
242 static void net_slirp_timer_mod(void *timer, int64_t expire_timer,
243 void *opaque)
245 SlirpTimer *t = timer;
246 timer_mod(&t->timer, expire_timer);
249 static void net_slirp_register_poll_fd(int fd, void *opaque)
251 #ifdef WIN32
252 AioContext *ctxt = qemu_get_aio_context();
254 if (WSAEventSelect(fd, event_notifier_get_handle(&ctxt->notifier),
255 FD_READ | FD_ACCEPT | FD_CLOSE |
256 FD_CONNECT | FD_WRITE | FD_OOB) != 0) {
257 error_setg_win32(&error_warn, WSAGetLastError(), "failed to WSAEventSelect()");
259 #endif
262 static void net_slirp_unregister_poll_fd(int fd, void *opaque)
264 #ifdef WIN32
265 if (WSAEventSelect(fd, NULL, 0) != 0) {
266 error_setg_win32(&error_warn, WSAGetLastError(), "failed to WSAEventSelect()");
268 #endif
271 static void net_slirp_notify(void *opaque)
273 qemu_notify_event();
276 static const SlirpCb slirp_cb = {
277 .send_packet = net_slirp_send_packet,
278 .guest_error = net_slirp_guest_error,
279 .clock_get_ns = net_slirp_clock_get_ns,
280 #if SLIRP_CHECK_VERSION(4,7,0)
281 .init_completed = net_slirp_init_completed,
282 .timer_new_opaque = net_slirp_timer_new_opaque,
283 #else
284 .timer_new = net_slirp_timer_new,
285 #endif
286 .timer_free = net_slirp_timer_free,
287 .timer_mod = net_slirp_timer_mod,
288 .register_poll_fd = net_slirp_register_poll_fd,
289 .unregister_poll_fd = net_slirp_unregister_poll_fd,
290 .notify = net_slirp_notify,
293 static int slirp_poll_to_gio(int events)
295 int ret = 0;
297 if (events & SLIRP_POLL_IN) {
298 ret |= G_IO_IN;
300 if (events & SLIRP_POLL_OUT) {
301 ret |= G_IO_OUT;
303 if (events & SLIRP_POLL_PRI) {
304 ret |= G_IO_PRI;
306 if (events & SLIRP_POLL_ERR) {
307 ret |= G_IO_ERR;
309 if (events & SLIRP_POLL_HUP) {
310 ret |= G_IO_HUP;
313 return ret;
316 static int net_slirp_add_poll(int fd, int events, void *opaque)
318 GArray *pollfds = opaque;
319 GPollFD pfd = {
320 .fd = fd,
321 .events = slirp_poll_to_gio(events),
323 int idx = pollfds->len;
324 g_array_append_val(pollfds, pfd);
325 return idx;
328 static int slirp_gio_to_poll(int events)
330 int ret = 0;
332 if (events & G_IO_IN) {
333 ret |= SLIRP_POLL_IN;
335 if (events & G_IO_OUT) {
336 ret |= SLIRP_POLL_OUT;
338 if (events & G_IO_PRI) {
339 ret |= SLIRP_POLL_PRI;
341 if (events & G_IO_ERR) {
342 ret |= SLIRP_POLL_ERR;
344 if (events & G_IO_HUP) {
345 ret |= SLIRP_POLL_HUP;
348 return ret;
351 static int net_slirp_get_revents(int idx, void *opaque)
353 GArray *pollfds = opaque;
355 return slirp_gio_to_poll(g_array_index(pollfds, GPollFD, idx).revents);
358 static void net_slirp_poll_notify(Notifier *notifier, void *data)
360 MainLoopPoll *poll = data;
361 SlirpState *s = container_of(notifier, SlirpState, poll_notifier);
363 switch (poll->state) {
364 case MAIN_LOOP_POLL_FILL:
365 slirp_pollfds_fill(s->slirp, &poll->timeout,
366 net_slirp_add_poll, poll->pollfds);
367 break;
368 case MAIN_LOOP_POLL_OK:
369 case MAIN_LOOP_POLL_ERR:
370 slirp_pollfds_poll(s->slirp, poll->state == MAIN_LOOP_POLL_ERR,
371 net_slirp_get_revents, poll->pollfds);
372 break;
373 default:
374 g_assert_not_reached();
378 static ssize_t
379 net_slirp_stream_read(void *buf, size_t size, void *opaque)
381 QEMUFile *f = opaque;
383 return qemu_get_buffer(f, buf, size);
386 static ssize_t
387 net_slirp_stream_write(const void *buf, size_t size, void *opaque)
389 QEMUFile *f = opaque;
391 qemu_put_buffer(f, buf, size);
392 if (qemu_file_get_error(f)) {
393 return -1;
396 return size;
399 static int net_slirp_state_load(QEMUFile *f, void *opaque, int version_id)
401 Slirp *slirp = opaque;
403 return slirp_state_load(slirp, version_id, net_slirp_stream_read, f);
406 static void net_slirp_state_save(QEMUFile *f, void *opaque)
408 Slirp *slirp = opaque;
410 slirp_state_save(slirp, net_slirp_stream_write, f);
413 static SaveVMHandlers savevm_slirp_state = {
414 .save_state = net_slirp_state_save,
415 .load_state = net_slirp_state_load,
418 static int net_slirp_init(NetClientState *peer, const char *model,
419 const char *name, int restricted,
420 bool ipv4, const char *vnetwork, const char *vhost,
421 bool ipv6, const char *vprefix6, int vprefix6_len,
422 const char *vhost6,
423 const char *vhostname, const char *tftp_export,
424 const char *bootfile, const char *vdhcp_start,
425 const char *vnameserver, const char *vnameserver6,
426 const char *smb_export, const char *vsmbserver,
427 const char **dnssearch, const char *vdomainname,
428 const char *tftp_server_name,
429 Error **errp)
431 /* default settings according to historic slirp */
432 struct in_addr net = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */
433 struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */
434 struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */
435 struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */
436 struct in_addr dns = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */
437 struct in6_addr ip6_prefix;
438 struct in6_addr ip6_host;
439 struct in6_addr ip6_dns;
440 #if defined(CONFIG_SMBD_COMMAND)
441 struct in_addr smbsrv = { .s_addr = 0 };
442 #endif
443 SlirpConfig cfg = { 0 };
444 NetClientState *nc;
445 SlirpState *s;
446 char buf[20];
447 uint32_t addr;
448 int shift;
449 char *end;
450 struct slirp_config_str *config;
452 if (!ipv4 && (vnetwork || vhost || vnameserver)) {
453 error_setg(errp, "IPv4 disabled but netmask/host/dns provided");
454 return -1;
457 if (!ipv6 && (vprefix6 || vhost6 || vnameserver6)) {
458 error_setg(errp, "IPv6 disabled but prefix/host6/dns6 provided");
459 return -1;
462 if (!ipv4 && !ipv6) {
463 /* It doesn't make sense to disable both */
464 error_setg(errp, "IPv4 and IPv6 disabled");
465 return -1;
468 if (vnetwork) {
469 if (get_str_sep(buf, sizeof(buf), &vnetwork, '/') < 0) {
470 if (!inet_aton(vnetwork, &net)) {
471 error_setg(errp, "Failed to parse netmask");
472 return -1;
474 addr = ntohl(net.s_addr);
475 if (!(addr & 0x80000000)) {
476 mask.s_addr = htonl(0xff000000); /* class A */
477 } else if ((addr & 0xfff00000) == 0xac100000) {
478 mask.s_addr = htonl(0xfff00000); /* priv. 172.16.0.0/12 */
479 } else if ((addr & 0xc0000000) == 0x80000000) {
480 mask.s_addr = htonl(0xffff0000); /* class B */
481 } else if ((addr & 0xffff0000) == 0xc0a80000) {
482 mask.s_addr = htonl(0xffff0000); /* priv. 192.168.0.0/16 */
483 } else if ((addr & 0xffff0000) == 0xc6120000) {
484 mask.s_addr = htonl(0xfffe0000); /* tests 198.18.0.0/15 */
485 } else if ((addr & 0xe0000000) == 0xe0000000) {
486 mask.s_addr = htonl(0xffffff00); /* class C */
487 } else {
488 mask.s_addr = htonl(0xfffffff0); /* multicast/reserved */
490 } else {
491 if (!inet_aton(buf, &net)) {
492 error_setg(errp, "Failed to parse netmask");
493 return -1;
495 shift = strtol(vnetwork, &end, 10);
496 if (*end != '\0') {
497 if (!inet_aton(vnetwork, &mask)) {
498 error_setg(errp,
499 "Failed to parse netmask (trailing chars)");
500 return -1;
502 } else if (shift < 4 || shift > 32) {
503 error_setg(errp,
504 "Invalid netmask provided (must be in range 4-32)");
505 return -1;
506 } else {
507 mask.s_addr = htonl(0xffffffff << (32 - shift));
510 net.s_addr &= mask.s_addr;
511 host.s_addr = net.s_addr | (htonl(0x0202) & ~mask.s_addr);
512 dhcp.s_addr = net.s_addr | (htonl(0x020f) & ~mask.s_addr);
513 dns.s_addr = net.s_addr | (htonl(0x0203) & ~mask.s_addr);
516 if (vhost && !inet_aton(vhost, &host)) {
517 error_setg(errp, "Failed to parse host");
518 return -1;
520 if ((host.s_addr & mask.s_addr) != net.s_addr) {
521 error_setg(errp, "Host doesn't belong to network");
522 return -1;
525 if (vnameserver && !inet_aton(vnameserver, &dns)) {
526 error_setg(errp, "Failed to parse DNS");
527 return -1;
529 if (restricted && (dns.s_addr & mask.s_addr) != net.s_addr) {
530 error_setg(errp, "DNS doesn't belong to network");
531 return -1;
533 if (dns.s_addr == host.s_addr) {
534 error_setg(errp, "DNS must be different from host");
535 return -1;
538 if (vdhcp_start && !inet_aton(vdhcp_start, &dhcp)) {
539 error_setg(errp, "Failed to parse DHCP start address");
540 return -1;
542 if ((dhcp.s_addr & mask.s_addr) != net.s_addr) {
543 error_setg(errp, "DHCP doesn't belong to network");
544 return -1;
546 if (dhcp.s_addr == host.s_addr || dhcp.s_addr == dns.s_addr) {
547 error_setg(errp, "DHCP must be different from host and DNS");
548 return -1;
551 #if defined(CONFIG_SMBD_COMMAND)
552 if (vsmbserver && !inet_aton(vsmbserver, &smbsrv)) {
553 error_setg(errp, "Failed to parse SMB address");
554 return -1;
556 #endif
558 if (!vprefix6) {
559 vprefix6 = "fec0::";
561 if (!inet_pton(AF_INET6, vprefix6, &ip6_prefix)) {
562 error_setg(errp, "Failed to parse IPv6 prefix");
563 return -1;
566 if (!vprefix6_len) {
567 vprefix6_len = 64;
569 if (vprefix6_len < 0 || vprefix6_len > 126) {
570 error_setg(errp,
571 "Invalid IPv6 prefix provided "
572 "(IPv6 prefix length must be between 0 and 126)");
573 return -1;
576 if (vhost6) {
577 if (!inet_pton(AF_INET6, vhost6, &ip6_host)) {
578 error_setg(errp, "Failed to parse IPv6 host");
579 return -1;
581 if (!in6_equal_net(&ip6_prefix, &ip6_host, vprefix6_len)) {
582 error_setg(errp, "IPv6 Host doesn't belong to network");
583 return -1;
585 } else {
586 ip6_host = ip6_prefix;
587 ip6_host.s6_addr[15] |= 2;
590 if (vnameserver6) {
591 if (!inet_pton(AF_INET6, vnameserver6, &ip6_dns)) {
592 error_setg(errp, "Failed to parse IPv6 DNS");
593 return -1;
595 if (restricted && !in6_equal_net(&ip6_prefix, &ip6_dns, vprefix6_len)) {
596 error_setg(errp, "IPv6 DNS doesn't belong to network");
597 return -1;
599 } else {
600 ip6_dns = ip6_prefix;
601 ip6_dns.s6_addr[15] |= 3;
604 if (vdomainname && !*vdomainname) {
605 error_setg(errp, "'domainname' parameter cannot be empty");
606 return -1;
609 if (vdomainname && strlen(vdomainname) > 255) {
610 error_setg(errp, "'domainname' parameter cannot exceed 255 bytes");
611 return -1;
614 if (vhostname && strlen(vhostname) > 255) {
615 error_setg(errp, "'vhostname' parameter cannot exceed 255 bytes");
616 return -1;
619 if (tftp_server_name && strlen(tftp_server_name) > 255) {
620 error_setg(errp, "'tftp-server-name' parameter cannot exceed 255 bytes");
621 return -1;
624 nc = qemu_new_net_client(&net_slirp_info, peer, model, name);
626 qemu_set_info_str(nc, "net=%s,restrict=%s", inet_ntoa(net),
627 restricted ? "on" : "off");
629 s = DO_UPCAST(SlirpState, nc, nc);
631 cfg.version = SLIRP_CHECK_VERSION(4,7,0) ? 4 : 1;
632 cfg.restricted = restricted;
633 cfg.in_enabled = ipv4;
634 cfg.vnetwork = net;
635 cfg.vnetmask = mask;
636 cfg.vhost = host;
637 cfg.in6_enabled = ipv6;
638 cfg.vprefix_addr6 = ip6_prefix;
639 cfg.vprefix_len = vprefix6_len;
640 cfg.vhost6 = ip6_host;
641 cfg.vhostname = vhostname;
642 cfg.tftp_server_name = tftp_server_name;
643 cfg.tftp_path = tftp_export;
644 cfg.bootfile = bootfile;
645 cfg.vdhcp_start = dhcp;
646 cfg.vnameserver = dns;
647 cfg.vnameserver6 = ip6_dns;
648 cfg.vdnssearch = dnssearch;
649 cfg.vdomainname = vdomainname;
650 s->slirp = slirp_new(&cfg, &slirp_cb, s);
651 QTAILQ_INSERT_TAIL(&slirp_stacks, s, entry);
654 * Make sure the current bitstream version of slirp is 4, to avoid
655 * QEMU migration incompatibilities, if upstream slirp bumped the
656 * version.
658 * FIXME: use bitfields of features? teach libslirp to save with
659 * specific version?
661 g_assert(slirp_state_version() == 4);
662 register_savevm_live("slirp", 0, slirp_state_version(),
663 &savevm_slirp_state, s->slirp);
665 s->poll_notifier.notify = net_slirp_poll_notify;
666 main_loop_poll_add_notifier(&s->poll_notifier);
668 for (config = slirp_configs; config; config = config->next) {
669 if (config->flags & SLIRP_CFG_HOSTFWD) {
670 if (slirp_hostfwd(s, config->str, errp) < 0) {
671 goto error;
673 } else {
674 if (slirp_guestfwd(s, config->str, errp) < 0) {
675 goto error;
679 #if defined(CONFIG_SMBD_COMMAND)
680 if (smb_export) {
681 if (slirp_smb(s, smb_export, smbsrv, errp) < 0) {
682 goto error;
685 #endif
687 s->exit_notifier.notify = slirp_smb_exit;
688 qemu_add_exit_notifier(&s->exit_notifier);
689 return 0;
691 error:
692 qemu_del_net_client(nc);
693 return -1;
696 static SlirpState *slirp_lookup(Monitor *mon, const char *id)
698 if (id) {
699 NetClientState *nc = qemu_find_netdev(id);
700 if (!nc) {
701 monitor_printf(mon, "unrecognized netdev id '%s'\n", id);
702 return NULL;
704 if (strcmp(nc->model, "user")) {
705 monitor_printf(mon, "invalid device specified\n");
706 return NULL;
708 return DO_UPCAST(SlirpState, nc, nc);
709 } else {
710 if (QTAILQ_EMPTY(&slirp_stacks)) {
711 monitor_printf(mon, "user mode network stack not in use\n");
712 return NULL;
714 return QTAILQ_FIRST(&slirp_stacks);
718 void hmp_hostfwd_remove(Monitor *mon, const QDict *qdict)
720 struct in_addr host_addr = { .s_addr = INADDR_ANY };
721 int host_port;
722 char buf[256];
723 const char *src_str, *p;
724 SlirpState *s;
725 int is_udp = 0;
726 int err;
727 const char *arg1 = qdict_get_str(qdict, "arg1");
728 const char *arg2 = qdict_get_try_str(qdict, "arg2");
730 if (arg2) {
731 s = slirp_lookup(mon, arg1);
732 src_str = arg2;
733 } else {
734 s = slirp_lookup(mon, NULL);
735 src_str = arg1;
737 if (!s) {
738 return;
741 p = src_str;
742 if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
743 goto fail_syntax;
746 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
747 is_udp = 0;
748 } else if (!strcmp(buf, "udp")) {
749 is_udp = 1;
750 } else {
751 goto fail_syntax;
754 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
755 goto fail_syntax;
757 if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
758 goto fail_syntax;
761 if (qemu_strtoi(p, NULL, 10, &host_port)) {
762 goto fail_syntax;
765 err = slirp_remove_hostfwd(s->slirp, is_udp, host_addr, host_port);
767 monitor_printf(mon, "host forwarding rule for %s %s\n", src_str,
768 err ? "not found" : "removed");
769 return;
771 fail_syntax:
772 monitor_printf(mon, "invalid format\n");
775 static int slirp_hostfwd(SlirpState *s, const char *redir_str, Error **errp)
777 struct in_addr host_addr = { .s_addr = INADDR_ANY };
778 struct in_addr guest_addr = { .s_addr = 0 };
779 int host_port, guest_port;
780 const char *p;
781 char buf[256];
782 int is_udp;
783 char *end;
784 const char *fail_reason = "Unknown reason";
786 p = redir_str;
787 if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
788 fail_reason = "No : separators";
789 goto fail_syntax;
791 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
792 is_udp = 0;
793 } else if (!strcmp(buf, "udp")) {
794 is_udp = 1;
795 } else {
796 fail_reason = "Bad protocol name";
797 goto fail_syntax;
800 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
801 fail_reason = "Missing : separator";
802 goto fail_syntax;
804 if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
805 fail_reason = "Bad host address";
806 goto fail_syntax;
809 if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {
810 fail_reason = "Bad host port separator";
811 goto fail_syntax;
813 host_port = strtol(buf, &end, 0);
814 if (*end != '\0' || host_port < 0 || host_port > 65535) {
815 fail_reason = "Bad host port";
816 goto fail_syntax;
819 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
820 fail_reason = "Missing guest address";
821 goto fail_syntax;
823 if (buf[0] != '\0' && !inet_aton(buf, &guest_addr)) {
824 fail_reason = "Bad guest address";
825 goto fail_syntax;
828 guest_port = strtol(p, &end, 0);
829 if (*end != '\0' || guest_port < 1 || guest_port > 65535) {
830 fail_reason = "Bad guest port";
831 goto fail_syntax;
834 if (slirp_add_hostfwd(s->slirp, is_udp, host_addr, host_port, guest_addr,
835 guest_port) < 0) {
836 error_setg(errp, "Could not set up host forwarding rule '%s'",
837 redir_str);
838 return -1;
840 return 0;
842 fail_syntax:
843 error_setg(errp, "Invalid host forwarding rule '%s' (%s)", redir_str,
844 fail_reason);
845 return -1;
848 void hmp_hostfwd_add(Monitor *mon, const QDict *qdict)
850 const char *redir_str;
851 SlirpState *s;
852 const char *arg1 = qdict_get_str(qdict, "arg1");
853 const char *arg2 = qdict_get_try_str(qdict, "arg2");
855 if (arg2) {
856 s = slirp_lookup(mon, arg1);
857 redir_str = arg2;
858 } else {
859 s = slirp_lookup(mon, NULL);
860 redir_str = arg1;
862 if (s) {
863 Error *err = NULL;
864 if (slirp_hostfwd(s, redir_str, &err) < 0) {
865 error_report_err(err);
871 #if defined(CONFIG_SMBD_COMMAND)
873 /* automatic user mode samba server configuration */
874 static void slirp_smb_cleanup(SlirpState *s)
876 int ret;
878 if (s->smb_dir) {
879 gchar *cmd = g_strdup_printf("rm -rf %s", s->smb_dir);
880 ret = system(cmd);
881 if (ret == -1 || !WIFEXITED(ret)) {
882 error_report("'%s' failed.", cmd);
883 } else if (WEXITSTATUS(ret)) {
884 error_report("'%s' failed. Error code: %d",
885 cmd, WEXITSTATUS(ret));
887 g_free(cmd);
888 g_free(s->smb_dir);
889 s->smb_dir = NULL;
893 static int slirp_smb(SlirpState* s, const char *exported_dir,
894 struct in_addr vserver_addr, Error **errp)
896 char *smb_conf;
897 char *smb_cmdline;
898 struct passwd *passwd;
899 FILE *f;
901 passwd = getpwuid(geteuid());
902 if (!passwd) {
903 error_setg(errp, "Failed to retrieve user name");
904 return -1;
907 if (access(CONFIG_SMBD_COMMAND, F_OK)) {
908 error_setg(errp, "Could not find '%s', please install it",
909 CONFIG_SMBD_COMMAND);
910 return -1;
913 if (access(exported_dir, R_OK | X_OK)) {
914 error_setg(errp, "Error accessing shared directory '%s': %s",
915 exported_dir, strerror(errno));
916 return -1;
919 s->smb_dir = g_dir_make_tmp("qemu-smb.XXXXXX", NULL);
920 if (!s->smb_dir) {
921 error_setg(errp, "Could not create samba server dir");
922 return -1;
924 smb_conf = g_strdup_printf("%s/%s", s->smb_dir, "smb.conf");
926 f = fopen(smb_conf, "w");
927 if (!f) {
928 slirp_smb_cleanup(s);
929 error_setg(errp,
930 "Could not create samba server configuration file '%s'",
931 smb_conf);
932 g_free(smb_conf);
933 return -1;
935 fprintf(f,
936 "[global]\n"
937 "private dir=%s\n"
938 "interfaces=127.0.0.1\n"
939 "bind interfaces only=yes\n"
940 "pid directory=%s\n"
941 "lock directory=%s\n"
942 "state directory=%s\n"
943 "cache directory=%s\n"
944 "ncalrpc dir=%s/ncalrpc\n"
945 "log file=%s/log.smbd\n"
946 "smb passwd file=%s/smbpasswd\n"
947 "security = user\n"
948 "map to guest = Bad User\n"
949 "load printers = no\n"
950 "printing = bsd\n"
951 "disable spoolss = yes\n"
952 "usershare max shares = 0\n"
953 "[qemu]\n"
954 "path=%s\n"
955 "read only=no\n"
956 "guest ok=yes\n"
957 "force user=%s\n",
958 s->smb_dir,
959 s->smb_dir,
960 s->smb_dir,
961 s->smb_dir,
962 s->smb_dir,
963 s->smb_dir,
964 s->smb_dir,
965 s->smb_dir,
966 exported_dir,
967 passwd->pw_name
969 fclose(f);
971 smb_cmdline = g_strdup_printf("%s -l %s -s %s",
972 CONFIG_SMBD_COMMAND, s->smb_dir, smb_conf);
973 g_free(smb_conf);
975 if (slirp_add_exec(s->slirp, smb_cmdline, &vserver_addr, 139) < 0 ||
976 slirp_add_exec(s->slirp, smb_cmdline, &vserver_addr, 445) < 0) {
977 slirp_smb_cleanup(s);
978 g_free(smb_cmdline);
979 error_setg(errp, "Conflicting/invalid smbserver address");
980 return -1;
982 g_free(smb_cmdline);
983 return 0;
986 #endif /* defined(CONFIG_SMBD_COMMAND) */
988 static int guestfwd_can_read(void *opaque)
990 struct GuestFwd *fwd = opaque;
991 return slirp_socket_can_recv(fwd->slirp, fwd->server, fwd->port);
994 static void guestfwd_read(void *opaque, const uint8_t *buf, int size)
996 struct GuestFwd *fwd = opaque;
997 slirp_socket_recv(fwd->slirp, fwd->server, fwd->port, buf, size);
1000 static ssize_t guestfwd_write(const void *buf, size_t len, void *chr)
1002 return qemu_chr_fe_write_all(chr, buf, len);
1005 static int slirp_guestfwd(SlirpState *s, const char *config_str, Error **errp)
1007 /* TODO: IPv6 */
1008 struct in_addr server = { .s_addr = 0 };
1009 struct GuestFwd *fwd;
1010 const char *p;
1011 char buf[128];
1012 char *end;
1013 int port;
1015 p = config_str;
1016 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1017 goto fail_syntax;
1019 if (strcmp(buf, "tcp") && buf[0] != '\0') {
1020 goto fail_syntax;
1022 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1023 goto fail_syntax;
1025 if (buf[0] != '\0' && !inet_aton(buf, &server)) {
1026 goto fail_syntax;
1028 if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {
1029 goto fail_syntax;
1031 port = strtol(buf, &end, 10);
1032 if (*end != '\0' || port < 1 || port > 65535) {
1033 goto fail_syntax;
1036 snprintf(buf, sizeof(buf), "guestfwd.tcp.%d", port);
1038 if (g_str_has_prefix(p, "cmd:")) {
1039 if (slirp_add_exec(s->slirp, &p[4], &server, port) < 0) {
1040 error_setg(errp, "Conflicting/invalid host:port in guest "
1041 "forwarding rule '%s'", config_str);
1042 return -1;
1044 } else {
1045 Error *err = NULL;
1047 * FIXME: sure we want to support implicit
1048 * muxed monitors here?
1050 Chardev *chr = qemu_chr_new_mux_mon(buf, p, NULL);
1052 if (!chr) {
1053 error_setg(errp, "Could not open guest forwarding device '%s'",
1054 buf);
1055 return -1;
1058 fwd = g_new(struct GuestFwd, 1);
1059 qemu_chr_fe_init(&fwd->hd, chr, &err);
1060 if (err) {
1061 error_propagate(errp, err);
1062 object_unparent(OBJECT(chr));
1063 g_free(fwd);
1064 return -1;
1067 if (slirp_add_guestfwd(s->slirp, guestfwd_write, &fwd->hd,
1068 &server, port) < 0) {
1069 error_setg(errp, "Conflicting/invalid host:port in guest "
1070 "forwarding rule '%s'", config_str);
1071 qemu_chr_fe_deinit(&fwd->hd, true);
1072 g_free(fwd);
1073 return -1;
1075 fwd->server = server;
1076 fwd->port = port;
1077 fwd->slirp = s->slirp;
1079 qemu_chr_fe_set_handlers(&fwd->hd, guestfwd_can_read, guestfwd_read,
1080 NULL, NULL, fwd, NULL, true);
1081 s->fwd = g_slist_append(s->fwd, fwd);
1083 return 0;
1085 fail_syntax:
1086 error_setg(errp, "Invalid guest forwarding rule '%s'", config_str);
1087 return -1;
1090 void hmp_info_usernet(Monitor *mon, const QDict *qdict)
1092 SlirpState *s;
1094 QTAILQ_FOREACH(s, &slirp_stacks, entry) {
1095 int id;
1096 bool got_hub_id = net_hub_id_for_client(&s->nc, &id) == 0;
1097 char *info = slirp_connection_info(s->slirp);
1098 monitor_printf(mon, "Hub %d (%s):\n%s",
1099 got_hub_id ? id : -1,
1100 s->nc.name, info);
1101 g_free(info);
1105 static void
1106 net_init_slirp_configs(const StringList *fwd, int flags)
1108 while (fwd) {
1109 struct slirp_config_str *config;
1111 config = g_malloc0(sizeof(*config));
1112 pstrcpy(config->str, sizeof(config->str), fwd->value->str);
1113 config->flags = flags;
1114 config->next = slirp_configs;
1115 slirp_configs = config;
1117 fwd = fwd->next;
1121 static const char **slirp_dnssearch(const StringList *dnsname)
1123 const StringList *c = dnsname;
1124 size_t i = 0, num_opts = 0;
1125 const char **ret;
1127 while (c) {
1128 num_opts++;
1129 c = c->next;
1132 if (num_opts == 0) {
1133 return NULL;
1136 ret = g_malloc((num_opts + 1) * sizeof(*ret));
1137 c = dnsname;
1138 while (c) {
1139 ret[i++] = c->value->str;
1140 c = c->next;
1142 ret[i] = NULL;
1143 return ret;
1146 int net_init_slirp(const Netdev *netdev, const char *name,
1147 NetClientState *peer, Error **errp)
1149 struct slirp_config_str *config;
1150 char *vnet;
1151 int ret;
1152 const NetdevUserOptions *user;
1153 const char **dnssearch;
1154 bool ipv4 = true, ipv6 = true;
1156 assert(netdev->type == NET_CLIENT_DRIVER_USER);
1157 user = &netdev->u.user;
1159 if ((user->has_ipv6 && user->ipv6 && !user->has_ipv4) ||
1160 (user->has_ipv4 && !user->ipv4)) {
1161 ipv4 = 0;
1163 if ((user->has_ipv4 && user->ipv4 && !user->has_ipv6) ||
1164 (user->has_ipv6 && !user->ipv6)) {
1165 ipv6 = 0;
1168 vnet = user->net ? g_strdup(user->net) :
1169 user->ip ? g_strdup_printf("%s/24", user->ip) :
1170 NULL;
1172 dnssearch = slirp_dnssearch(user->dnssearch);
1174 /* all optional fields are initialized to "all bits zero" */
1176 net_init_slirp_configs(user->hostfwd, SLIRP_CFG_HOSTFWD);
1177 net_init_slirp_configs(user->guestfwd, 0);
1179 ret = net_slirp_init(peer, "user", name, user->q_restrict,
1180 ipv4, vnet, user->host,
1181 ipv6, user->ipv6_prefix, user->ipv6_prefixlen,
1182 user->ipv6_host, user->hostname, user->tftp,
1183 user->bootfile, user->dhcpstart,
1184 user->dns, user->ipv6_dns, user->smb,
1185 user->smbserver, dnssearch, user->domainname,
1186 user->tftp_server_name, errp);
1188 while (slirp_configs) {
1189 config = slirp_configs;
1190 slirp_configs = config->next;
1191 g_free(config);
1194 g_free(vnet);
1195 g_free(dnssearch);
1197 return ret;