blkverify: add missing coroutine_fn annotations
[qemu.git] / net / slirp.c
blob8679be64442037d5d03a8b62f3f502a29a11d679
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 qemu_fd_register(fd);
254 static void net_slirp_unregister_poll_fd(int fd, void *opaque)
256 /* no qemu_fd_unregister */
259 static void net_slirp_notify(void *opaque)
261 qemu_notify_event();
264 static const SlirpCb slirp_cb = {
265 .send_packet = net_slirp_send_packet,
266 .guest_error = net_slirp_guest_error,
267 .clock_get_ns = net_slirp_clock_get_ns,
268 #if SLIRP_CHECK_VERSION(4,7,0)
269 .init_completed = net_slirp_init_completed,
270 .timer_new_opaque = net_slirp_timer_new_opaque,
271 #else
272 .timer_new = net_slirp_timer_new,
273 #endif
274 .timer_free = net_slirp_timer_free,
275 .timer_mod = net_slirp_timer_mod,
276 .register_poll_fd = net_slirp_register_poll_fd,
277 .unregister_poll_fd = net_slirp_unregister_poll_fd,
278 .notify = net_slirp_notify,
281 static int slirp_poll_to_gio(int events)
283 int ret = 0;
285 if (events & SLIRP_POLL_IN) {
286 ret |= G_IO_IN;
288 if (events & SLIRP_POLL_OUT) {
289 ret |= G_IO_OUT;
291 if (events & SLIRP_POLL_PRI) {
292 ret |= G_IO_PRI;
294 if (events & SLIRP_POLL_ERR) {
295 ret |= G_IO_ERR;
297 if (events & SLIRP_POLL_HUP) {
298 ret |= G_IO_HUP;
301 return ret;
304 static int net_slirp_add_poll(int fd, int events, void *opaque)
306 GArray *pollfds = opaque;
307 GPollFD pfd = {
308 .fd = fd,
309 .events = slirp_poll_to_gio(events),
311 int idx = pollfds->len;
312 g_array_append_val(pollfds, pfd);
313 return idx;
316 static int slirp_gio_to_poll(int events)
318 int ret = 0;
320 if (events & G_IO_IN) {
321 ret |= SLIRP_POLL_IN;
323 if (events & G_IO_OUT) {
324 ret |= SLIRP_POLL_OUT;
326 if (events & G_IO_PRI) {
327 ret |= SLIRP_POLL_PRI;
329 if (events & G_IO_ERR) {
330 ret |= SLIRP_POLL_ERR;
332 if (events & G_IO_HUP) {
333 ret |= SLIRP_POLL_HUP;
336 return ret;
339 static int net_slirp_get_revents(int idx, void *opaque)
341 GArray *pollfds = opaque;
343 return slirp_gio_to_poll(g_array_index(pollfds, GPollFD, idx).revents);
346 static void net_slirp_poll_notify(Notifier *notifier, void *data)
348 MainLoopPoll *poll = data;
349 SlirpState *s = container_of(notifier, SlirpState, poll_notifier);
351 switch (poll->state) {
352 case MAIN_LOOP_POLL_FILL:
353 slirp_pollfds_fill(s->slirp, &poll->timeout,
354 net_slirp_add_poll, poll->pollfds);
355 break;
356 case MAIN_LOOP_POLL_OK:
357 case MAIN_LOOP_POLL_ERR:
358 slirp_pollfds_poll(s->slirp, poll->state == MAIN_LOOP_POLL_ERR,
359 net_slirp_get_revents, poll->pollfds);
360 break;
361 default:
362 g_assert_not_reached();
366 static ssize_t
367 net_slirp_stream_read(void *buf, size_t size, void *opaque)
369 QEMUFile *f = opaque;
371 return qemu_get_buffer(f, buf, size);
374 static ssize_t
375 net_slirp_stream_write(const void *buf, size_t size, void *opaque)
377 QEMUFile *f = opaque;
379 qemu_put_buffer(f, buf, size);
380 if (qemu_file_get_error(f)) {
381 return -1;
384 return size;
387 static int net_slirp_state_load(QEMUFile *f, void *opaque, int version_id)
389 Slirp *slirp = opaque;
391 return slirp_state_load(slirp, version_id, net_slirp_stream_read, f);
394 static void net_slirp_state_save(QEMUFile *f, void *opaque)
396 Slirp *slirp = opaque;
398 slirp_state_save(slirp, net_slirp_stream_write, f);
401 static SaveVMHandlers savevm_slirp_state = {
402 .save_state = net_slirp_state_save,
403 .load_state = net_slirp_state_load,
406 static int net_slirp_init(NetClientState *peer, const char *model,
407 const char *name, int restricted,
408 bool ipv4, const char *vnetwork, const char *vhost,
409 bool ipv6, const char *vprefix6, int vprefix6_len,
410 const char *vhost6,
411 const char *vhostname, const char *tftp_export,
412 const char *bootfile, const char *vdhcp_start,
413 const char *vnameserver, const char *vnameserver6,
414 const char *smb_export, const char *vsmbserver,
415 const char **dnssearch, const char *vdomainname,
416 const char *tftp_server_name,
417 Error **errp)
419 /* default settings according to historic slirp */
420 struct in_addr net = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */
421 struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */
422 struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */
423 struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */
424 struct in_addr dns = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */
425 struct in6_addr ip6_prefix;
426 struct in6_addr ip6_host;
427 struct in6_addr ip6_dns;
428 #if defined(CONFIG_SMBD_COMMAND)
429 struct in_addr smbsrv = { .s_addr = 0 };
430 #endif
431 SlirpConfig cfg = { 0 };
432 NetClientState *nc;
433 SlirpState *s;
434 char buf[20];
435 uint32_t addr;
436 int shift;
437 char *end;
438 struct slirp_config_str *config;
440 if (!ipv4 && (vnetwork || vhost || vnameserver)) {
441 error_setg(errp, "IPv4 disabled but netmask/host/dns provided");
442 return -1;
445 if (!ipv6 && (vprefix6 || vhost6 || vnameserver6)) {
446 error_setg(errp, "IPv6 disabled but prefix/host6/dns6 provided");
447 return -1;
450 if (!ipv4 && !ipv6) {
451 /* It doesn't make sense to disable both */
452 error_setg(errp, "IPv4 and IPv6 disabled");
453 return -1;
456 if (vnetwork) {
457 if (get_str_sep(buf, sizeof(buf), &vnetwork, '/') < 0) {
458 if (!inet_aton(vnetwork, &net)) {
459 error_setg(errp, "Failed to parse netmask");
460 return -1;
462 addr = ntohl(net.s_addr);
463 if (!(addr & 0x80000000)) {
464 mask.s_addr = htonl(0xff000000); /* class A */
465 } else if ((addr & 0xfff00000) == 0xac100000) {
466 mask.s_addr = htonl(0xfff00000); /* priv. 172.16.0.0/12 */
467 } else if ((addr & 0xc0000000) == 0x80000000) {
468 mask.s_addr = htonl(0xffff0000); /* class B */
469 } else if ((addr & 0xffff0000) == 0xc0a80000) {
470 mask.s_addr = htonl(0xffff0000); /* priv. 192.168.0.0/16 */
471 } else if ((addr & 0xffff0000) == 0xc6120000) {
472 mask.s_addr = htonl(0xfffe0000); /* tests 198.18.0.0/15 */
473 } else if ((addr & 0xe0000000) == 0xe0000000) {
474 mask.s_addr = htonl(0xffffff00); /* class C */
475 } else {
476 mask.s_addr = htonl(0xfffffff0); /* multicast/reserved */
478 } else {
479 if (!inet_aton(buf, &net)) {
480 error_setg(errp, "Failed to parse netmask");
481 return -1;
483 shift = strtol(vnetwork, &end, 10);
484 if (*end != '\0') {
485 if (!inet_aton(vnetwork, &mask)) {
486 error_setg(errp,
487 "Failed to parse netmask (trailing chars)");
488 return -1;
490 } else if (shift < 4 || shift > 32) {
491 error_setg(errp,
492 "Invalid netmask provided (must be in range 4-32)");
493 return -1;
494 } else {
495 mask.s_addr = htonl(0xffffffff << (32 - shift));
498 net.s_addr &= mask.s_addr;
499 host.s_addr = net.s_addr | (htonl(0x0202) & ~mask.s_addr);
500 dhcp.s_addr = net.s_addr | (htonl(0x020f) & ~mask.s_addr);
501 dns.s_addr = net.s_addr | (htonl(0x0203) & ~mask.s_addr);
504 if (vhost && !inet_aton(vhost, &host)) {
505 error_setg(errp, "Failed to parse host");
506 return -1;
508 if ((host.s_addr & mask.s_addr) != net.s_addr) {
509 error_setg(errp, "Host doesn't belong to network");
510 return -1;
513 if (vnameserver && !inet_aton(vnameserver, &dns)) {
514 error_setg(errp, "Failed to parse DNS");
515 return -1;
517 if (restricted && (dns.s_addr & mask.s_addr) != net.s_addr) {
518 error_setg(errp, "DNS doesn't belong to network");
519 return -1;
521 if (dns.s_addr == host.s_addr) {
522 error_setg(errp, "DNS must be different from host");
523 return -1;
526 if (vdhcp_start && !inet_aton(vdhcp_start, &dhcp)) {
527 error_setg(errp, "Failed to parse DHCP start address");
528 return -1;
530 if ((dhcp.s_addr & mask.s_addr) != net.s_addr) {
531 error_setg(errp, "DHCP doesn't belong to network");
532 return -1;
534 if (dhcp.s_addr == host.s_addr || dhcp.s_addr == dns.s_addr) {
535 error_setg(errp, "DHCP must be different from host and DNS");
536 return -1;
539 #if defined(CONFIG_SMBD_COMMAND)
540 if (vsmbserver && !inet_aton(vsmbserver, &smbsrv)) {
541 error_setg(errp, "Failed to parse SMB address");
542 return -1;
544 #endif
546 if (!vprefix6) {
547 vprefix6 = "fec0::";
549 if (!inet_pton(AF_INET6, vprefix6, &ip6_prefix)) {
550 error_setg(errp, "Failed to parse IPv6 prefix");
551 return -1;
554 if (!vprefix6_len) {
555 vprefix6_len = 64;
557 if (vprefix6_len < 0 || vprefix6_len > 126) {
558 error_setg(errp,
559 "Invalid IPv6 prefix provided "
560 "(IPv6 prefix length must be between 0 and 126)");
561 return -1;
564 if (vhost6) {
565 if (!inet_pton(AF_INET6, vhost6, &ip6_host)) {
566 error_setg(errp, "Failed to parse IPv6 host");
567 return -1;
569 if (!in6_equal_net(&ip6_prefix, &ip6_host, vprefix6_len)) {
570 error_setg(errp, "IPv6 Host doesn't belong to network");
571 return -1;
573 } else {
574 ip6_host = ip6_prefix;
575 ip6_host.s6_addr[15] |= 2;
578 if (vnameserver6) {
579 if (!inet_pton(AF_INET6, vnameserver6, &ip6_dns)) {
580 error_setg(errp, "Failed to parse IPv6 DNS");
581 return -1;
583 if (restricted && !in6_equal_net(&ip6_prefix, &ip6_dns, vprefix6_len)) {
584 error_setg(errp, "IPv6 DNS doesn't belong to network");
585 return -1;
587 } else {
588 ip6_dns = ip6_prefix;
589 ip6_dns.s6_addr[15] |= 3;
592 if (vdomainname && !*vdomainname) {
593 error_setg(errp, "'domainname' parameter cannot be empty");
594 return -1;
597 if (vdomainname && strlen(vdomainname) > 255) {
598 error_setg(errp, "'domainname' parameter cannot exceed 255 bytes");
599 return -1;
602 if (vhostname && strlen(vhostname) > 255) {
603 error_setg(errp, "'vhostname' parameter cannot exceed 255 bytes");
604 return -1;
607 if (tftp_server_name && strlen(tftp_server_name) > 255) {
608 error_setg(errp, "'tftp-server-name' parameter cannot exceed 255 bytes");
609 return -1;
612 nc = qemu_new_net_client(&net_slirp_info, peer, model, name);
614 snprintf(nc->info_str, sizeof(nc->info_str),
615 "net=%s,restrict=%s", inet_ntoa(net),
616 restricted ? "on" : "off");
618 s = DO_UPCAST(SlirpState, nc, nc);
620 cfg.version = SLIRP_CHECK_VERSION(4,7,0) ? 4 : 1;
621 cfg.restricted = restricted;
622 cfg.in_enabled = ipv4;
623 cfg.vnetwork = net;
624 cfg.vnetmask = mask;
625 cfg.vhost = host;
626 cfg.in6_enabled = ipv6;
627 cfg.vprefix_addr6 = ip6_prefix;
628 cfg.vprefix_len = vprefix6_len;
629 cfg.vhost6 = ip6_host;
630 cfg.vhostname = vhostname;
631 cfg.tftp_server_name = tftp_server_name;
632 cfg.tftp_path = tftp_export;
633 cfg.bootfile = bootfile;
634 cfg.vdhcp_start = dhcp;
635 cfg.vnameserver = dns;
636 cfg.vnameserver6 = ip6_dns;
637 cfg.vdnssearch = dnssearch;
638 cfg.vdomainname = vdomainname;
639 s->slirp = slirp_new(&cfg, &slirp_cb, s);
640 QTAILQ_INSERT_TAIL(&slirp_stacks, s, entry);
643 * Make sure the current bitstream version of slirp is 4, to avoid
644 * QEMU migration incompatibilities, if upstream slirp bumped the
645 * version.
647 * FIXME: use bitfields of features? teach libslirp to save with
648 * specific version?
650 g_assert(slirp_state_version() == 4);
651 register_savevm_live("slirp", 0, slirp_state_version(),
652 &savevm_slirp_state, s->slirp);
654 s->poll_notifier.notify = net_slirp_poll_notify;
655 main_loop_poll_add_notifier(&s->poll_notifier);
657 for (config = slirp_configs; config; config = config->next) {
658 if (config->flags & SLIRP_CFG_HOSTFWD) {
659 if (slirp_hostfwd(s, config->str, errp) < 0) {
660 goto error;
662 } else {
663 if (slirp_guestfwd(s, config->str, errp) < 0) {
664 goto error;
668 #if defined(CONFIG_SMBD_COMMAND)
669 if (smb_export) {
670 if (slirp_smb(s, smb_export, smbsrv, errp) < 0) {
671 goto error;
674 #endif
676 s->exit_notifier.notify = slirp_smb_exit;
677 qemu_add_exit_notifier(&s->exit_notifier);
678 return 0;
680 error:
681 qemu_del_net_client(nc);
682 return -1;
685 static SlirpState *slirp_lookup(Monitor *mon, const char *id)
687 if (id) {
688 NetClientState *nc = qemu_find_netdev(id);
689 if (!nc) {
690 monitor_printf(mon, "unrecognized netdev id '%s'\n", id);
691 return NULL;
693 if (strcmp(nc->model, "user")) {
694 monitor_printf(mon, "invalid device specified\n");
695 return NULL;
697 return DO_UPCAST(SlirpState, nc, nc);
698 } else {
699 if (QTAILQ_EMPTY(&slirp_stacks)) {
700 monitor_printf(mon, "user mode network stack not in use\n");
701 return NULL;
703 return QTAILQ_FIRST(&slirp_stacks);
707 void hmp_hostfwd_remove(Monitor *mon, const QDict *qdict)
709 struct in_addr host_addr = { .s_addr = INADDR_ANY };
710 int host_port;
711 char buf[256];
712 const char *src_str, *p;
713 SlirpState *s;
714 int is_udp = 0;
715 int err;
716 const char *arg1 = qdict_get_str(qdict, "arg1");
717 const char *arg2 = qdict_get_try_str(qdict, "arg2");
719 if (arg2) {
720 s = slirp_lookup(mon, arg1);
721 src_str = arg2;
722 } else {
723 s = slirp_lookup(mon, NULL);
724 src_str = arg1;
726 if (!s) {
727 return;
730 p = src_str;
731 if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
732 goto fail_syntax;
735 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
736 is_udp = 0;
737 } else if (!strcmp(buf, "udp")) {
738 is_udp = 1;
739 } else {
740 goto fail_syntax;
743 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
744 goto fail_syntax;
746 if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
747 goto fail_syntax;
750 if (qemu_strtoi(p, NULL, 10, &host_port)) {
751 goto fail_syntax;
754 err = slirp_remove_hostfwd(s->slirp, is_udp, host_addr, host_port);
756 monitor_printf(mon, "host forwarding rule for %s %s\n", src_str,
757 err ? "not found" : "removed");
758 return;
760 fail_syntax:
761 monitor_printf(mon, "invalid format\n");
764 static int slirp_hostfwd(SlirpState *s, const char *redir_str, Error **errp)
766 struct in_addr host_addr = { .s_addr = INADDR_ANY };
767 struct in_addr guest_addr = { .s_addr = 0 };
768 int host_port, guest_port;
769 const char *p;
770 char buf[256];
771 int is_udp;
772 char *end;
773 const char *fail_reason = "Unknown reason";
775 p = redir_str;
776 if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
777 fail_reason = "No : separators";
778 goto fail_syntax;
780 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
781 is_udp = 0;
782 } else if (!strcmp(buf, "udp")) {
783 is_udp = 1;
784 } else {
785 fail_reason = "Bad protocol name";
786 goto fail_syntax;
789 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
790 fail_reason = "Missing : separator";
791 goto fail_syntax;
793 if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
794 fail_reason = "Bad host address";
795 goto fail_syntax;
798 if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {
799 fail_reason = "Bad host port separator";
800 goto fail_syntax;
802 host_port = strtol(buf, &end, 0);
803 if (*end != '\0' || host_port < 0 || host_port > 65535) {
804 fail_reason = "Bad host port";
805 goto fail_syntax;
808 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
809 fail_reason = "Missing guest address";
810 goto fail_syntax;
812 if (buf[0] != '\0' && !inet_aton(buf, &guest_addr)) {
813 fail_reason = "Bad guest address";
814 goto fail_syntax;
817 guest_port = strtol(p, &end, 0);
818 if (*end != '\0' || guest_port < 1 || guest_port > 65535) {
819 fail_reason = "Bad guest port";
820 goto fail_syntax;
823 if (slirp_add_hostfwd(s->slirp, is_udp, host_addr, host_port, guest_addr,
824 guest_port) < 0) {
825 error_setg(errp, "Could not set up host forwarding rule '%s'",
826 redir_str);
827 return -1;
829 return 0;
831 fail_syntax:
832 error_setg(errp, "Invalid host forwarding rule '%s' (%s)", redir_str,
833 fail_reason);
834 return -1;
837 void hmp_hostfwd_add(Monitor *mon, const QDict *qdict)
839 const char *redir_str;
840 SlirpState *s;
841 const char *arg1 = qdict_get_str(qdict, "arg1");
842 const char *arg2 = qdict_get_try_str(qdict, "arg2");
844 if (arg2) {
845 s = slirp_lookup(mon, arg1);
846 redir_str = arg2;
847 } else {
848 s = slirp_lookup(mon, NULL);
849 redir_str = arg1;
851 if (s) {
852 Error *err = NULL;
853 if (slirp_hostfwd(s, redir_str, &err) < 0) {
854 error_report_err(err);
860 #if defined(CONFIG_SMBD_COMMAND)
862 /* automatic user mode samba server configuration */
863 static void slirp_smb_cleanup(SlirpState *s)
865 int ret;
867 if (s->smb_dir) {
868 gchar *cmd = g_strdup_printf("rm -rf %s", s->smb_dir);
869 ret = system(cmd);
870 if (ret == -1 || !WIFEXITED(ret)) {
871 error_report("'%s' failed.", cmd);
872 } else if (WEXITSTATUS(ret)) {
873 error_report("'%s' failed. Error code: %d",
874 cmd, WEXITSTATUS(ret));
876 g_free(cmd);
877 g_free(s->smb_dir);
878 s->smb_dir = NULL;
882 static int slirp_smb(SlirpState* s, const char *exported_dir,
883 struct in_addr vserver_addr, Error **errp)
885 char *smb_conf;
886 char *smb_cmdline;
887 struct passwd *passwd;
888 FILE *f;
890 passwd = getpwuid(geteuid());
891 if (!passwd) {
892 error_setg(errp, "Failed to retrieve user name");
893 return -1;
896 if (access(CONFIG_SMBD_COMMAND, F_OK)) {
897 error_setg(errp, "Could not find '%s', please install it",
898 CONFIG_SMBD_COMMAND);
899 return -1;
902 if (access(exported_dir, R_OK | X_OK)) {
903 error_setg(errp, "Error accessing shared directory '%s': %s",
904 exported_dir, strerror(errno));
905 return -1;
908 s->smb_dir = g_dir_make_tmp("qemu-smb.XXXXXX", NULL);
909 if (!s->smb_dir) {
910 error_setg(errp, "Could not create samba server dir");
911 return -1;
913 smb_conf = g_strdup_printf("%s/%s", s->smb_dir, "smb.conf");
915 f = fopen(smb_conf, "w");
916 if (!f) {
917 slirp_smb_cleanup(s);
918 error_setg(errp,
919 "Could not create samba server configuration file '%s'",
920 smb_conf);
921 g_free(smb_conf);
922 return -1;
924 fprintf(f,
925 "[global]\n"
926 "private dir=%s\n"
927 "interfaces=127.0.0.1\n"
928 "bind interfaces only=yes\n"
929 "pid directory=%s\n"
930 "lock directory=%s\n"
931 "state directory=%s\n"
932 "cache directory=%s\n"
933 "ncalrpc dir=%s/ncalrpc\n"
934 "log file=%s/log.smbd\n"
935 "smb passwd file=%s/smbpasswd\n"
936 "security = user\n"
937 "map to guest = Bad User\n"
938 "load printers = no\n"
939 "printing = bsd\n"
940 "disable spoolss = yes\n"
941 "usershare max shares = 0\n"
942 "[qemu]\n"
943 "path=%s\n"
944 "read only=no\n"
945 "guest ok=yes\n"
946 "force user=%s\n",
947 s->smb_dir,
948 s->smb_dir,
949 s->smb_dir,
950 s->smb_dir,
951 s->smb_dir,
952 s->smb_dir,
953 s->smb_dir,
954 s->smb_dir,
955 exported_dir,
956 passwd->pw_name
958 fclose(f);
960 smb_cmdline = g_strdup_printf("%s -l %s -s %s",
961 CONFIG_SMBD_COMMAND, s->smb_dir, smb_conf);
962 g_free(smb_conf);
964 if (slirp_add_exec(s->slirp, smb_cmdline, &vserver_addr, 139) < 0 ||
965 slirp_add_exec(s->slirp, smb_cmdline, &vserver_addr, 445) < 0) {
966 slirp_smb_cleanup(s);
967 g_free(smb_cmdline);
968 error_setg(errp, "Conflicting/invalid smbserver address");
969 return -1;
971 g_free(smb_cmdline);
972 return 0;
975 #endif /* defined(CONFIG_SMBD_COMMAND) */
977 static int guestfwd_can_read(void *opaque)
979 struct GuestFwd *fwd = opaque;
980 return slirp_socket_can_recv(fwd->slirp, fwd->server, fwd->port);
983 static void guestfwd_read(void *opaque, const uint8_t *buf, int size)
985 struct GuestFwd *fwd = opaque;
986 slirp_socket_recv(fwd->slirp, fwd->server, fwd->port, buf, size);
989 static ssize_t guestfwd_write(const void *buf, size_t len, void *chr)
991 return qemu_chr_fe_write_all(chr, buf, len);
994 static int slirp_guestfwd(SlirpState *s, const char *config_str, Error **errp)
996 /* TODO: IPv6 */
997 struct in_addr server = { .s_addr = 0 };
998 struct GuestFwd *fwd;
999 const char *p;
1000 char buf[128];
1001 char *end;
1002 int port;
1004 p = config_str;
1005 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1006 goto fail_syntax;
1008 if (strcmp(buf, "tcp") && buf[0] != '\0') {
1009 goto fail_syntax;
1011 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1012 goto fail_syntax;
1014 if (buf[0] != '\0' && !inet_aton(buf, &server)) {
1015 goto fail_syntax;
1017 if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {
1018 goto fail_syntax;
1020 port = strtol(buf, &end, 10);
1021 if (*end != '\0' || port < 1 || port > 65535) {
1022 goto fail_syntax;
1025 snprintf(buf, sizeof(buf), "guestfwd.tcp.%d", port);
1027 if (g_str_has_prefix(p, "cmd:")) {
1028 if (slirp_add_exec(s->slirp, &p[4], &server, port) < 0) {
1029 error_setg(errp, "Conflicting/invalid host:port in guest "
1030 "forwarding rule '%s'", config_str);
1031 return -1;
1033 } else {
1034 Error *err = NULL;
1036 * FIXME: sure we want to support implicit
1037 * muxed monitors here?
1039 Chardev *chr = qemu_chr_new_mux_mon(buf, p, NULL);
1041 if (!chr) {
1042 error_setg(errp, "Could not open guest forwarding device '%s'",
1043 buf);
1044 return -1;
1047 fwd = g_new(struct GuestFwd, 1);
1048 qemu_chr_fe_init(&fwd->hd, chr, &err);
1049 if (err) {
1050 error_propagate(errp, err);
1051 object_unparent(OBJECT(chr));
1052 g_free(fwd);
1053 return -1;
1056 if (slirp_add_guestfwd(s->slirp, guestfwd_write, &fwd->hd,
1057 &server, port) < 0) {
1058 error_setg(errp, "Conflicting/invalid host:port in guest "
1059 "forwarding rule '%s'", config_str);
1060 qemu_chr_fe_deinit(&fwd->hd, true);
1061 g_free(fwd);
1062 return -1;
1064 fwd->server = server;
1065 fwd->port = port;
1066 fwd->slirp = s->slirp;
1068 qemu_chr_fe_set_handlers(&fwd->hd, guestfwd_can_read, guestfwd_read,
1069 NULL, NULL, fwd, NULL, true);
1070 s->fwd = g_slist_append(s->fwd, fwd);
1072 return 0;
1074 fail_syntax:
1075 error_setg(errp, "Invalid guest forwarding rule '%s'", config_str);
1076 return -1;
1079 void hmp_info_usernet(Monitor *mon, const QDict *qdict)
1081 SlirpState *s;
1083 QTAILQ_FOREACH(s, &slirp_stacks, entry) {
1084 int id;
1085 bool got_hub_id = net_hub_id_for_client(&s->nc, &id) == 0;
1086 char *info = slirp_connection_info(s->slirp);
1087 monitor_printf(mon, "Hub %d (%s):\n%s",
1088 got_hub_id ? id : -1,
1089 s->nc.name, info);
1090 g_free(info);
1094 static void
1095 net_init_slirp_configs(const StringList *fwd, int flags)
1097 while (fwd) {
1098 struct slirp_config_str *config;
1100 config = g_malloc0(sizeof(*config));
1101 pstrcpy(config->str, sizeof(config->str), fwd->value->str);
1102 config->flags = flags;
1103 config->next = slirp_configs;
1104 slirp_configs = config;
1106 fwd = fwd->next;
1110 static const char **slirp_dnssearch(const StringList *dnsname)
1112 const StringList *c = dnsname;
1113 size_t i = 0, num_opts = 0;
1114 const char **ret;
1116 while (c) {
1117 num_opts++;
1118 c = c->next;
1121 if (num_opts == 0) {
1122 return NULL;
1125 ret = g_malloc((num_opts + 1) * sizeof(*ret));
1126 c = dnsname;
1127 while (c) {
1128 ret[i++] = c->value->str;
1129 c = c->next;
1131 ret[i] = NULL;
1132 return ret;
1135 int net_init_slirp(const Netdev *netdev, const char *name,
1136 NetClientState *peer, Error **errp)
1138 struct slirp_config_str *config;
1139 char *vnet;
1140 int ret;
1141 const NetdevUserOptions *user;
1142 const char **dnssearch;
1143 bool ipv4 = true, ipv6 = true;
1145 assert(netdev->type == NET_CLIENT_DRIVER_USER);
1146 user = &netdev->u.user;
1148 if ((user->has_ipv6 && user->ipv6 && !user->has_ipv4) ||
1149 (user->has_ipv4 && !user->ipv4)) {
1150 ipv4 = 0;
1152 if ((user->has_ipv4 && user->ipv4 && !user->has_ipv6) ||
1153 (user->has_ipv6 && !user->ipv6)) {
1154 ipv6 = 0;
1157 vnet = user->has_net ? g_strdup(user->net) :
1158 user->has_ip ? g_strdup_printf("%s/24", user->ip) :
1159 NULL;
1161 dnssearch = slirp_dnssearch(user->dnssearch);
1163 /* all optional fields are initialized to "all bits zero" */
1165 net_init_slirp_configs(user->hostfwd, SLIRP_CFG_HOSTFWD);
1166 net_init_slirp_configs(user->guestfwd, 0);
1168 ret = net_slirp_init(peer, "user", name, user->q_restrict,
1169 ipv4, vnet, user->host,
1170 ipv6, user->ipv6_prefix, user->ipv6_prefixlen,
1171 user->ipv6_host, user->hostname, user->tftp,
1172 user->bootfile, user->dhcpstart,
1173 user->dns, user->ipv6_dns, user->smb,
1174 user->smbserver, dnssearch, user->domainname,
1175 user->tftp_server_name, errp);
1177 while (slirp_configs) {
1178 config = slirp_configs;
1179 slirp_configs = config->next;
1180 g_free(config);
1183 g_free(vnet);
1184 g_free(dnssearch);
1186 return ret;