xref: /openbmc/qemu/net/slirp.c (revision 503bb0b9)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qemu/log.h"
27 #include "net/slirp.h"
28 
29 
30 #ifndef _WIN32
31 #include <pwd.h>
32 #include <sys/wait.h>
33 #endif
34 #include "net/net.h"
35 #include "clients.h"
36 #include "hub.h"
37 #include "monitor/monitor.h"
38 #include "qemu/error-report.h"
39 #include "qemu/sockets.h"
40 #include "slirp/libslirp.h"
41 #include "chardev/char-fe.h"
42 #include "sysemu/sysemu.h"
43 #include "qemu/cutils.h"
44 #include "qapi/error.h"
45 #include "qapi/qmp/qdict.h"
46 #include "util.h"
47 
48 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
49 {
50     const char *p, *p1;
51     int len;
52     p = *pp;
53     p1 = strchr(p, sep);
54     if (!p1)
55         return -1;
56     len = p1 - p;
57     p1++;
58     if (buf_size > 0) {
59         if (len > buf_size - 1)
60             len = buf_size - 1;
61         memcpy(buf, p, len);
62         buf[len] = '\0';
63     }
64     *pp = p1;
65     return 0;
66 }
67 
68 /* slirp network adapter */
69 
70 #define SLIRP_CFG_HOSTFWD 1
71 
72 struct slirp_config_str {
73     struct slirp_config_str *next;
74     int flags;
75     char str[1024];
76 };
77 
78 struct GuestFwd {
79     CharBackend hd;
80     struct in_addr server;
81     int port;
82     Slirp *slirp;
83 };
84 
85 typedef struct SlirpState {
86     NetClientState nc;
87     QTAILQ_ENTRY(SlirpState) entry;
88     Slirp *slirp;
89     Notifier poll_notifier;
90     Notifier exit_notifier;
91 #ifndef _WIN32
92     gchar *smb_dir;
93 #endif
94     GSList *fwd;
95 } SlirpState;
96 
97 static struct slirp_config_str *slirp_configs;
98 static QTAILQ_HEAD(, SlirpState) slirp_stacks =
99     QTAILQ_HEAD_INITIALIZER(slirp_stacks);
100 
101 static int slirp_hostfwd(SlirpState *s, const char *redir_str, Error **errp);
102 static int slirp_guestfwd(SlirpState *s, const char *config_str, Error **errp);
103 
104 #ifndef _WIN32
105 static int slirp_smb(SlirpState *s, const char *exported_dir,
106                      struct in_addr vserver_addr, Error **errp);
107 static void slirp_smb_cleanup(SlirpState *s);
108 #else
109 static inline void slirp_smb_cleanup(SlirpState *s) { }
110 #endif
111 
112 static ssize_t net_slirp_send_packet(const void *pkt, size_t pkt_len,
113                                      void *opaque)
114 {
115     SlirpState *s = opaque;
116 
117     return qemu_send_packet(&s->nc, pkt, pkt_len);
118 }
119 
120 static ssize_t net_slirp_receive(NetClientState *nc, const uint8_t *buf, size_t size)
121 {
122     SlirpState *s = DO_UPCAST(SlirpState, nc, nc);
123 
124     slirp_input(s->slirp, buf, size);
125 
126     return size;
127 }
128 
129 static void slirp_smb_exit(Notifier *n, void *data)
130 {
131     SlirpState *s = container_of(n, SlirpState, exit_notifier);
132     slirp_smb_cleanup(s);
133 }
134 
135 static void slirp_free_fwd(gpointer data)
136 {
137     struct GuestFwd *fwd = data;
138 
139     qemu_chr_fe_deinit(&fwd->hd, true);
140     g_free(data);
141 }
142 
143 static void net_slirp_cleanup(NetClientState *nc)
144 {
145     SlirpState *s = DO_UPCAST(SlirpState, nc, nc);
146 
147     g_slist_free_full(s->fwd, slirp_free_fwd);
148     main_loop_poll_remove_notifier(&s->poll_notifier);
149     slirp_cleanup(s->slirp);
150     if (s->exit_notifier.notify) {
151         qemu_remove_exit_notifier(&s->exit_notifier);
152     }
153     slirp_smb_cleanup(s);
154     QTAILQ_REMOVE(&slirp_stacks, s, entry);
155 }
156 
157 static NetClientInfo net_slirp_info = {
158     .type = NET_CLIENT_DRIVER_USER,
159     .size = sizeof(SlirpState),
160     .receive = net_slirp_receive,
161     .cleanup = net_slirp_cleanup,
162 };
163 
164 static void net_slirp_guest_error(const char *msg, void *opaque)
165 {
166     qemu_log_mask(LOG_GUEST_ERROR, "%s", msg);
167 }
168 
169 static int64_t net_slirp_clock_get_ns(void *opaque)
170 {
171     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
172 }
173 
174 static void *net_slirp_timer_new(SlirpTimerCb cb,
175                                  void *cb_opaque, void *opaque)
176 {
177     return timer_new_full(NULL, QEMU_CLOCK_VIRTUAL,
178                           SCALE_MS, QEMU_TIMER_ATTR_EXTERNAL,
179                           cb, cb_opaque);
180 }
181 
182 static void net_slirp_timer_free(void *timer, void *opaque)
183 {
184     timer_del(timer);
185     timer_free(timer);
186 }
187 
188 static void net_slirp_timer_mod(void *timer, int64_t expire_timer,
189                                 void *opaque)
190 {
191     timer_mod(timer, expire_timer);
192 }
193 
194 static void net_slirp_register_poll_fd(int fd, void *opaque)
195 {
196     qemu_fd_register(fd);
197 }
198 
199 static void net_slirp_unregister_poll_fd(int fd, void *opaque)
200 {
201     /* no qemu_fd_unregister */
202 }
203 
204 static void net_slirp_notify(void *opaque)
205 {
206     qemu_notify_event();
207 }
208 
209 static const SlirpCb slirp_cb = {
210     .send_packet = net_slirp_send_packet,
211     .guest_error = net_slirp_guest_error,
212     .clock_get_ns = net_slirp_clock_get_ns,
213     .timer_new = net_slirp_timer_new,
214     .timer_free = net_slirp_timer_free,
215     .timer_mod = net_slirp_timer_mod,
216     .register_poll_fd = net_slirp_register_poll_fd,
217     .unregister_poll_fd = net_slirp_unregister_poll_fd,
218     .notify = net_slirp_notify,
219 };
220 
221 static int slirp_poll_to_gio(int events)
222 {
223     int ret = 0;
224 
225     if (events & SLIRP_POLL_IN) {
226         ret |= G_IO_IN;
227     }
228     if (events & SLIRP_POLL_OUT) {
229         ret |= G_IO_OUT;
230     }
231     if (events & SLIRP_POLL_PRI) {
232         ret |= G_IO_PRI;
233     }
234     if (events & SLIRP_POLL_ERR) {
235         ret |= G_IO_ERR;
236     }
237     if (events & SLIRP_POLL_HUP) {
238         ret |= G_IO_HUP;
239     }
240 
241     return ret;
242 }
243 
244 static int net_slirp_add_poll(int fd, int events, void *opaque)
245 {
246     GArray *pollfds = opaque;
247     GPollFD pfd = {
248         .fd = fd,
249         .events = slirp_poll_to_gio(events),
250     };
251     int idx = pollfds->len;
252     g_array_append_val(pollfds, pfd);
253     return idx;
254 }
255 
256 static int slirp_gio_to_poll(int events)
257 {
258     int ret = 0;
259 
260     if (events & G_IO_IN) {
261         ret |= SLIRP_POLL_IN;
262     }
263     if (events & G_IO_OUT) {
264         ret |= SLIRP_POLL_OUT;
265     }
266     if (events & G_IO_PRI) {
267         ret |= SLIRP_POLL_PRI;
268     }
269     if (events & G_IO_ERR) {
270         ret |= SLIRP_POLL_ERR;
271     }
272     if (events & G_IO_HUP) {
273         ret |= SLIRP_POLL_HUP;
274     }
275 
276     return ret;
277 }
278 
279 static int net_slirp_get_revents(int idx, void *opaque)
280 {
281     GArray *pollfds = opaque;
282 
283     return slirp_gio_to_poll(g_array_index(pollfds, GPollFD, idx).revents);
284 }
285 
286 static void net_slirp_poll_notify(Notifier *notifier, void *data)
287 {
288     MainLoopPoll *poll = data;
289     SlirpState *s = container_of(notifier, SlirpState, poll_notifier);
290 
291     switch (poll->state) {
292     case MAIN_LOOP_POLL_FILL:
293         slirp_pollfds_fill(s->slirp, &poll->timeout,
294                            net_slirp_add_poll, poll->pollfds);
295         break;
296     case MAIN_LOOP_POLL_OK:
297     case MAIN_LOOP_POLL_ERR:
298         slirp_pollfds_poll(s->slirp, poll->state == MAIN_LOOP_POLL_ERR,
299                            net_slirp_get_revents, poll->pollfds);
300         break;
301     default:
302         g_assert_not_reached();
303     }
304 }
305 
306 static int net_slirp_init(NetClientState *peer, const char *model,
307                           const char *name, int restricted,
308                           bool ipv4, const char *vnetwork, const char *vhost,
309                           bool ipv6, const char *vprefix6, int vprefix6_len,
310                           const char *vhost6,
311                           const char *vhostname, const char *tftp_export,
312                           const char *bootfile, const char *vdhcp_start,
313                           const char *vnameserver, const char *vnameserver6,
314                           const char *smb_export, const char *vsmbserver,
315                           const char **dnssearch, const char *vdomainname,
316                           const char *tftp_server_name,
317                           Error **errp)
318 {
319     /* default settings according to historic slirp */
320     struct in_addr net  = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */
321     struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */
322     struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */
323     struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */
324     struct in_addr dns  = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */
325     struct in6_addr ip6_prefix;
326     struct in6_addr ip6_host;
327     struct in6_addr ip6_dns;
328 #ifndef _WIN32
329     struct in_addr smbsrv = { .s_addr = 0 };
330 #endif
331     NetClientState *nc;
332     SlirpState *s;
333     char buf[20];
334     uint32_t addr;
335     int shift;
336     char *end;
337     struct slirp_config_str *config;
338 
339     if (!ipv4 && (vnetwork || vhost || vnameserver)) {
340         error_setg(errp, "IPv4 disabled but netmask/host/dns provided");
341         return -1;
342     }
343 
344     if (!ipv6 && (vprefix6 || vhost6 || vnameserver6)) {
345         error_setg(errp, "IPv6 disabled but prefix/host6/dns6 provided");
346         return -1;
347     }
348 
349     if (!ipv4 && !ipv6) {
350         /* It doesn't make sense to disable both */
351         error_setg(errp, "IPv4 and IPv6 disabled");
352         return -1;
353     }
354 
355     if (vnetwork) {
356         if (get_str_sep(buf, sizeof(buf), &vnetwork, '/') < 0) {
357             if (!inet_aton(vnetwork, &net)) {
358                 error_setg(errp, "Failed to parse netmask");
359                 return -1;
360             }
361             addr = ntohl(net.s_addr);
362             if (!(addr & 0x80000000)) {
363                 mask.s_addr = htonl(0xff000000); /* class A */
364             } else if ((addr & 0xfff00000) == 0xac100000) {
365                 mask.s_addr = htonl(0xfff00000); /* priv. 172.16.0.0/12 */
366             } else if ((addr & 0xc0000000) == 0x80000000) {
367                 mask.s_addr = htonl(0xffff0000); /* class B */
368             } else if ((addr & 0xffff0000) == 0xc0a80000) {
369                 mask.s_addr = htonl(0xffff0000); /* priv. 192.168.0.0/16 */
370             } else if ((addr & 0xffff0000) == 0xc6120000) {
371                 mask.s_addr = htonl(0xfffe0000); /* tests 198.18.0.0/15 */
372             } else if ((addr & 0xe0000000) == 0xe0000000) {
373                 mask.s_addr = htonl(0xffffff00); /* class C */
374             } else {
375                 mask.s_addr = htonl(0xfffffff0); /* multicast/reserved */
376             }
377         } else {
378             if (!inet_aton(buf, &net)) {
379                 error_setg(errp, "Failed to parse netmask");
380                 return -1;
381             }
382             shift = strtol(vnetwork, &end, 10);
383             if (*end != '\0') {
384                 if (!inet_aton(vnetwork, &mask)) {
385                     error_setg(errp,
386                                "Failed to parse netmask (trailing chars)");
387                     return -1;
388                 }
389             } else if (shift < 4 || shift > 32) {
390                 error_setg(errp,
391                            "Invalid netmask provided (must be in range 4-32)");
392                 return -1;
393             } else {
394                 mask.s_addr = htonl(0xffffffff << (32 - shift));
395             }
396         }
397         net.s_addr &= mask.s_addr;
398         host.s_addr = net.s_addr | (htonl(0x0202) & ~mask.s_addr);
399         dhcp.s_addr = net.s_addr | (htonl(0x020f) & ~mask.s_addr);
400         dns.s_addr  = net.s_addr | (htonl(0x0203) & ~mask.s_addr);
401     }
402 
403     if (vhost && !inet_aton(vhost, &host)) {
404         error_setg(errp, "Failed to parse host");
405         return -1;
406     }
407     if ((host.s_addr & mask.s_addr) != net.s_addr) {
408         error_setg(errp, "Host doesn't belong to network");
409         return -1;
410     }
411 
412     if (vnameserver && !inet_aton(vnameserver, &dns)) {
413         error_setg(errp, "Failed to parse DNS");
414         return -1;
415     }
416     if ((dns.s_addr & mask.s_addr) != net.s_addr) {
417         error_setg(errp, "DNS doesn't belong to network");
418         return -1;
419     }
420     if (dns.s_addr == host.s_addr) {
421         error_setg(errp, "DNS must be different from host");
422         return -1;
423     }
424 
425     if (vdhcp_start && !inet_aton(vdhcp_start, &dhcp)) {
426         error_setg(errp, "Failed to parse DHCP start address");
427         return -1;
428     }
429     if ((dhcp.s_addr & mask.s_addr) != net.s_addr) {
430         error_setg(errp, "DHCP doesn't belong to network");
431         return -1;
432     }
433     if (dhcp.s_addr == host.s_addr || dhcp.s_addr == dns.s_addr) {
434         error_setg(errp, "DNS must be different from host and DNS");
435         return -1;
436     }
437 
438 #ifndef _WIN32
439     if (vsmbserver && !inet_aton(vsmbserver, &smbsrv)) {
440         error_setg(errp, "Failed to parse SMB address");
441         return -1;
442     }
443 #endif
444 
445     if (!vprefix6) {
446         vprefix6 = "fec0::";
447     }
448     if (!inet_pton(AF_INET6, vprefix6, &ip6_prefix)) {
449         error_setg(errp, "Failed to parse IPv6 prefix");
450         return -1;
451     }
452 
453     if (!vprefix6_len) {
454         vprefix6_len = 64;
455     }
456     if (vprefix6_len < 0 || vprefix6_len > 126) {
457         error_setg(errp,
458                    "Invalid prefix provided (prefix len must be in range 0-126");
459         return -1;
460     }
461 
462     if (vhost6) {
463         if (!inet_pton(AF_INET6, vhost6, &ip6_host)) {
464             error_setg(errp, "Failed to parse IPv6 host");
465             return -1;
466         }
467         if (!in6_equal_net(&ip6_prefix, &ip6_host, vprefix6_len)) {
468             error_setg(errp, "IPv6 Host doesn't belong to network");
469             return -1;
470         }
471     } else {
472         ip6_host = ip6_prefix;
473         ip6_host.s6_addr[15] |= 2;
474     }
475 
476     if (vnameserver6) {
477         if (!inet_pton(AF_INET6, vnameserver6, &ip6_dns)) {
478             error_setg(errp, "Failed to parse IPv6 DNS");
479             return -1;
480         }
481         if (!in6_equal_net(&ip6_prefix, &ip6_dns, vprefix6_len)) {
482             error_setg(errp, "IPv6 DNS doesn't belong to network");
483             return -1;
484         }
485     } else {
486         ip6_dns = ip6_prefix;
487         ip6_dns.s6_addr[15] |= 3;
488     }
489 
490     if (vdomainname && !*vdomainname) {
491         error_setg(errp, "'domainname' parameter cannot be empty");
492         return -1;
493     }
494 
495     if (vdomainname && strlen(vdomainname) > 255) {
496         error_setg(errp, "'domainname' parameter cannot exceed 255 bytes");
497         return -1;
498     }
499 
500     if (vhostname && strlen(vhostname) > 255) {
501         error_setg(errp, "'vhostname' parameter cannot exceed 255 bytes");
502         return -1;
503     }
504 
505     if (tftp_server_name && strlen(tftp_server_name) > 255) {
506         error_setg(errp, "'tftp-server-name' parameter cannot exceed 255 bytes");
507         return -1;
508     }
509 
510     nc = qemu_new_net_client(&net_slirp_info, peer, model, name);
511 
512     snprintf(nc->info_str, sizeof(nc->info_str),
513              "net=%s,restrict=%s", inet_ntoa(net),
514              restricted ? "on" : "off");
515 
516     s = DO_UPCAST(SlirpState, nc, nc);
517 
518     s->slirp = slirp_init(restricted, ipv4, net, mask, host,
519                           ipv6, ip6_prefix, vprefix6_len, ip6_host,
520                           vhostname, tftp_server_name,
521                           tftp_export, bootfile, dhcp,
522                           dns, ip6_dns, dnssearch, vdomainname,
523                           &slirp_cb, s);
524     QTAILQ_INSERT_TAIL(&slirp_stacks, s, entry);
525 
526     s->poll_notifier.notify = net_slirp_poll_notify;
527     main_loop_poll_add_notifier(&s->poll_notifier);
528 
529     for (config = slirp_configs; config; config = config->next) {
530         if (config->flags & SLIRP_CFG_HOSTFWD) {
531             if (slirp_hostfwd(s, config->str, errp) < 0) {
532                 goto error;
533             }
534         } else {
535             if (slirp_guestfwd(s, config->str, errp) < 0) {
536                 goto error;
537             }
538         }
539     }
540 #ifndef _WIN32
541     if (smb_export) {
542         if (slirp_smb(s, smb_export, smbsrv, errp) < 0) {
543             goto error;
544         }
545     }
546 #endif
547 
548     s->exit_notifier.notify = slirp_smb_exit;
549     qemu_add_exit_notifier(&s->exit_notifier);
550     return 0;
551 
552 error:
553     qemu_del_net_client(nc);
554     return -1;
555 }
556 
557 static SlirpState *slirp_lookup(Monitor *mon, const char *hub_id,
558                                 const char *name)
559 {
560     if (name) {
561         NetClientState *nc;
562         if (hub_id) {
563             nc = net_hub_find_client_by_name(strtol(hub_id, NULL, 0), name);
564             if (!nc) {
565                 monitor_printf(mon, "unrecognized (hub-id, stackname) pair\n");
566                 return NULL;
567             }
568             warn_report("Using 'hub-id' is deprecated, specify the netdev id "
569                         "directly instead");
570         } else {
571             nc = qemu_find_netdev(name);
572             if (!nc) {
573                 monitor_printf(mon, "unrecognized netdev id '%s'\n", name);
574                 return NULL;
575             }
576         }
577         if (strcmp(nc->model, "user")) {
578             monitor_printf(mon, "invalid device specified\n");
579             return NULL;
580         }
581         return DO_UPCAST(SlirpState, nc, nc);
582     } else {
583         if (QTAILQ_EMPTY(&slirp_stacks)) {
584             monitor_printf(mon, "user mode network stack not in use\n");
585             return NULL;
586         }
587         return QTAILQ_FIRST(&slirp_stacks);
588     }
589 }
590 
591 void hmp_hostfwd_remove(Monitor *mon, const QDict *qdict)
592 {
593     struct in_addr host_addr = { .s_addr = INADDR_ANY };
594     int host_port;
595     char buf[256];
596     const char *src_str, *p;
597     SlirpState *s;
598     int is_udp = 0;
599     int err;
600     const char *arg1 = qdict_get_str(qdict, "arg1");
601     const char *arg2 = qdict_get_try_str(qdict, "arg2");
602     const char *arg3 = qdict_get_try_str(qdict, "arg3");
603 
604     if (arg3) {
605         s = slirp_lookup(mon, arg1, arg2);
606         src_str = arg3;
607     } else if (arg2) {
608         s = slirp_lookup(mon, NULL, arg1);
609         src_str = arg2;
610     } else {
611         s = slirp_lookup(mon, NULL, NULL);
612         src_str = arg1;
613     }
614     if (!s) {
615         return;
616     }
617 
618     p = src_str;
619     if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
620         goto fail_syntax;
621     }
622 
623     if (!strcmp(buf, "tcp") || buf[0] == '\0') {
624         is_udp = 0;
625     } else if (!strcmp(buf, "udp")) {
626         is_udp = 1;
627     } else {
628         goto fail_syntax;
629     }
630 
631     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
632         goto fail_syntax;
633     }
634     if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
635         goto fail_syntax;
636     }
637 
638     if (qemu_strtoi(p, NULL, 10, &host_port)) {
639         goto fail_syntax;
640     }
641 
642     err = slirp_remove_hostfwd(s->slirp, is_udp, host_addr, host_port);
643 
644     monitor_printf(mon, "host forwarding rule for %s %s\n", src_str,
645                    err ? "not found" : "removed");
646     return;
647 
648  fail_syntax:
649     monitor_printf(mon, "invalid format\n");
650 }
651 
652 static int slirp_hostfwd(SlirpState *s, const char *redir_str, Error **errp)
653 {
654     struct in_addr host_addr = { .s_addr = INADDR_ANY };
655     struct in_addr guest_addr = { .s_addr = 0 };
656     int host_port, guest_port;
657     const char *p;
658     char buf[256];
659     int is_udp;
660     char *end;
661     const char *fail_reason = "Unknown reason";
662 
663     p = redir_str;
664     if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
665         fail_reason = "No : separators";
666         goto fail_syntax;
667     }
668     if (!strcmp(buf, "tcp") || buf[0] == '\0') {
669         is_udp = 0;
670     } else if (!strcmp(buf, "udp")) {
671         is_udp = 1;
672     } else {
673         fail_reason = "Bad protocol name";
674         goto fail_syntax;
675     }
676 
677     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
678         fail_reason = "Missing : separator";
679         goto fail_syntax;
680     }
681     if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
682         fail_reason = "Bad host address";
683         goto fail_syntax;
684     }
685 
686     if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {
687         fail_reason = "Bad host port separator";
688         goto fail_syntax;
689     }
690     host_port = strtol(buf, &end, 0);
691     if (*end != '\0' || host_port < 0 || host_port > 65535) {
692         fail_reason = "Bad host port";
693         goto fail_syntax;
694     }
695 
696     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
697         fail_reason = "Missing guest address";
698         goto fail_syntax;
699     }
700     if (buf[0] != '\0' && !inet_aton(buf, &guest_addr)) {
701         fail_reason = "Bad guest address";
702         goto fail_syntax;
703     }
704 
705     guest_port = strtol(p, &end, 0);
706     if (*end != '\0' || guest_port < 1 || guest_port > 65535) {
707         fail_reason = "Bad guest port";
708         goto fail_syntax;
709     }
710 
711     if (slirp_add_hostfwd(s->slirp, is_udp, host_addr, host_port, guest_addr,
712                           guest_port) < 0) {
713         error_setg(errp, "Could not set up host forwarding rule '%s'",
714                    redir_str);
715         return -1;
716     }
717     return 0;
718 
719  fail_syntax:
720     error_setg(errp, "Invalid host forwarding rule '%s' (%s)", redir_str,
721                fail_reason);
722     return -1;
723 }
724 
725 void hmp_hostfwd_add(Monitor *mon, const QDict *qdict)
726 {
727     const char *redir_str;
728     SlirpState *s;
729     const char *arg1 = qdict_get_str(qdict, "arg1");
730     const char *arg2 = qdict_get_try_str(qdict, "arg2");
731     const char *arg3 = qdict_get_try_str(qdict, "arg3");
732 
733     if (arg3) {
734         s = slirp_lookup(mon, arg1, arg2);
735         redir_str = arg3;
736     } else if (arg2) {
737         s = slirp_lookup(mon, NULL, arg1);
738         redir_str = arg2;
739     } else {
740         s = slirp_lookup(mon, NULL, NULL);
741         redir_str = arg1;
742     }
743     if (s) {
744         Error *err = NULL;
745         if (slirp_hostfwd(s, redir_str, &err) < 0) {
746             error_report_err(err);
747         }
748     }
749 
750 }
751 
752 #ifndef _WIN32
753 
754 /* automatic user mode samba server configuration */
755 static void slirp_smb_cleanup(SlirpState *s)
756 {
757     int ret;
758 
759     if (s->smb_dir) {
760         gchar *cmd = g_strdup_printf("rm -rf %s", s->smb_dir);
761         ret = system(cmd);
762         if (ret == -1 || !WIFEXITED(ret)) {
763             error_report("'%s' failed.", cmd);
764         } else if (WEXITSTATUS(ret)) {
765             error_report("'%s' failed. Error code: %d",
766                          cmd, WEXITSTATUS(ret));
767         }
768         g_free(cmd);
769         g_free(s->smb_dir);
770         s->smb_dir = NULL;
771     }
772 }
773 
774 static int slirp_smb(SlirpState* s, const char *exported_dir,
775                      struct in_addr vserver_addr, Error **errp)
776 {
777     char *smb_conf;
778     char *smb_cmdline;
779     struct passwd *passwd;
780     FILE *f;
781 
782     passwd = getpwuid(geteuid());
783     if (!passwd) {
784         error_setg(errp, "Failed to retrieve user name");
785         return -1;
786     }
787 
788     if (access(CONFIG_SMBD_COMMAND, F_OK)) {
789         error_setg(errp, "Could not find '%s', please install it",
790                    CONFIG_SMBD_COMMAND);
791         return -1;
792     }
793 
794     if (access(exported_dir, R_OK | X_OK)) {
795         error_setg(errp, "Error accessing shared directory '%s': %s",
796                    exported_dir, strerror(errno));
797         return -1;
798     }
799 
800     s->smb_dir = g_dir_make_tmp("qemu-smb.XXXXXX", NULL);
801     if (!s->smb_dir) {
802         error_setg(errp, "Could not create samba server dir");
803         return -1;
804     }
805     smb_conf = g_strdup_printf("%s/%s", s->smb_dir, "smb.conf");
806 
807     f = fopen(smb_conf, "w");
808     if (!f) {
809         slirp_smb_cleanup(s);
810         error_setg(errp,
811                    "Could not create samba server configuration file '%s'",
812                     smb_conf);
813         g_free(smb_conf);
814         return -1;
815     }
816     fprintf(f,
817             "[global]\n"
818             "private dir=%s\n"
819             "interfaces=127.0.0.1\n"
820             "bind interfaces only=yes\n"
821             "pid directory=%s\n"
822             "lock directory=%s\n"
823             "state directory=%s\n"
824             "cache directory=%s\n"
825             "ncalrpc dir=%s/ncalrpc\n"
826             "log file=%s/log.smbd\n"
827             "smb passwd file=%s/smbpasswd\n"
828             "security = user\n"
829             "map to guest = Bad User\n"
830             "load printers = no\n"
831             "printing = bsd\n"
832             "disable spoolss = yes\n"
833             "usershare max shares = 0\n"
834             "[qemu]\n"
835             "path=%s\n"
836             "read only=no\n"
837             "guest ok=yes\n"
838             "force user=%s\n",
839             s->smb_dir,
840             s->smb_dir,
841             s->smb_dir,
842             s->smb_dir,
843             s->smb_dir,
844             s->smb_dir,
845             s->smb_dir,
846             s->smb_dir,
847             exported_dir,
848             passwd->pw_name
849             );
850     fclose(f);
851 
852     smb_cmdline = g_strdup_printf("%s -l %s -s %s",
853              CONFIG_SMBD_COMMAND, s->smb_dir, smb_conf);
854     g_free(smb_conf);
855 
856     if (slirp_add_exec(s->slirp, smb_cmdline, &vserver_addr, 139) < 0 ||
857         slirp_add_exec(s->slirp, smb_cmdline, &vserver_addr, 445) < 0) {
858         slirp_smb_cleanup(s);
859         g_free(smb_cmdline);
860         error_setg(errp, "Conflicting/invalid smbserver address");
861         return -1;
862     }
863     g_free(smb_cmdline);
864     return 0;
865 }
866 
867 #endif /* !defined(_WIN32) */
868 
869 static int guestfwd_can_read(void *opaque)
870 {
871     struct GuestFwd *fwd = opaque;
872     return slirp_socket_can_recv(fwd->slirp, fwd->server, fwd->port);
873 }
874 
875 static void guestfwd_read(void *opaque, const uint8_t *buf, int size)
876 {
877     struct GuestFwd *fwd = opaque;
878     slirp_socket_recv(fwd->slirp, fwd->server, fwd->port, buf, size);
879 }
880 
881 static ssize_t guestfwd_write(const void *buf, size_t len, void *chr)
882 {
883     return qemu_chr_fe_write_all(chr, buf, len);
884 }
885 
886 static int slirp_guestfwd(SlirpState *s, const char *config_str, Error **errp)
887 {
888     struct in_addr server = { .s_addr = 0 };
889     struct GuestFwd *fwd;
890     const char *p;
891     char buf[128];
892     char *end;
893     int port;
894 
895     p = config_str;
896     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
897         goto fail_syntax;
898     }
899     if (strcmp(buf, "tcp") && buf[0] != '\0') {
900         goto fail_syntax;
901     }
902     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
903         goto fail_syntax;
904     }
905     if (buf[0] != '\0' && !inet_aton(buf, &server)) {
906         goto fail_syntax;
907     }
908     if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {
909         goto fail_syntax;
910     }
911     port = strtol(buf, &end, 10);
912     if (*end != '\0' || port < 1 || port > 65535) {
913         goto fail_syntax;
914     }
915 
916     snprintf(buf, sizeof(buf), "guestfwd.tcp.%d", port);
917 
918     if (g_str_has_prefix(p, "cmd:")) {
919         if (slirp_add_exec(s->slirp, &p[4], &server, port) < 0) {
920             error_setg(errp, "Conflicting/invalid host:port in guest "
921                        "forwarding rule '%s'", config_str);
922             return -1;
923         }
924     } else {
925         Error *err = NULL;
926         /*
927          * FIXME: sure we want to support implicit
928          * muxed monitors here?
929          */
930         Chardev *chr = qemu_chr_new_mux_mon(buf, p, NULL);
931 
932         if (!chr) {
933             error_setg(errp, "Could not open guest forwarding device '%s'",
934                        buf);
935             return -1;
936         }
937 
938         fwd = g_new(struct GuestFwd, 1);
939         qemu_chr_fe_init(&fwd->hd, chr, &err);
940         if (err) {
941             error_propagate(errp, err);
942             object_unparent(OBJECT(chr));
943             g_free(fwd);
944             return -1;
945         }
946 
947         if (slirp_add_guestfwd(s->slirp, guestfwd_write, &fwd->hd,
948                                &server, port) < 0) {
949             error_setg(errp, "Conflicting/invalid host:port in guest "
950                        "forwarding rule '%s'", config_str);
951             qemu_chr_fe_deinit(&fwd->hd, true);
952             g_free(fwd);
953             return -1;
954         }
955         fwd->server = server;
956         fwd->port = port;
957         fwd->slirp = s->slirp;
958 
959         qemu_chr_fe_set_handlers(&fwd->hd, guestfwd_can_read, guestfwd_read,
960                                  NULL, NULL, fwd, NULL, true);
961         s->fwd = g_slist_append(s->fwd, fwd);
962     }
963     return 0;
964 
965  fail_syntax:
966     error_setg(errp, "Invalid guest forwarding rule '%s'", config_str);
967     return -1;
968 }
969 
970 void hmp_info_usernet(Monitor *mon, const QDict *qdict)
971 {
972     SlirpState *s;
973 
974     QTAILQ_FOREACH(s, &slirp_stacks, entry) {
975         int id;
976         bool got_hub_id = net_hub_id_for_client(&s->nc, &id) == 0;
977         char *info = slirp_connection_info(s->slirp);
978         monitor_printf(mon, "Hub %d (%s):\n%s",
979                        got_hub_id ? id : -1,
980                        s->nc.name, info);
981         g_free(info);
982     }
983 }
984 
985 static void
986 net_init_slirp_configs(const StringList *fwd, int flags)
987 {
988     while (fwd) {
989         struct slirp_config_str *config;
990 
991         config = g_malloc0(sizeof(*config));
992         pstrcpy(config->str, sizeof(config->str), fwd->value->str);
993         config->flags = flags;
994         config->next = slirp_configs;
995         slirp_configs = config;
996 
997         fwd = fwd->next;
998     }
999 }
1000 
1001 static const char **slirp_dnssearch(const StringList *dnsname)
1002 {
1003     const StringList *c = dnsname;
1004     size_t i = 0, num_opts = 0;
1005     const char **ret;
1006 
1007     while (c) {
1008         num_opts++;
1009         c = c->next;
1010     }
1011 
1012     if (num_opts == 0) {
1013         return NULL;
1014     }
1015 
1016     ret = g_malloc((num_opts + 1) * sizeof(*ret));
1017     c = dnsname;
1018     while (c) {
1019         ret[i++] = c->value->str;
1020         c = c->next;
1021     }
1022     ret[i] = NULL;
1023     return ret;
1024 }
1025 
1026 int net_init_slirp(const Netdev *netdev, const char *name,
1027                    NetClientState *peer, Error **errp)
1028 {
1029     struct slirp_config_str *config;
1030     char *vnet;
1031     int ret;
1032     const NetdevUserOptions *user;
1033     const char **dnssearch;
1034     bool ipv4 = true, ipv6 = true;
1035 
1036     assert(netdev->type == NET_CLIENT_DRIVER_USER);
1037     user = &netdev->u.user;
1038 
1039     if ((user->has_ipv6 && user->ipv6 && !user->has_ipv4) ||
1040         (user->has_ipv4 && !user->ipv4)) {
1041         ipv4 = 0;
1042     }
1043     if ((user->has_ipv4 && user->ipv4 && !user->has_ipv6) ||
1044         (user->has_ipv6 && !user->ipv6)) {
1045         ipv6 = 0;
1046     }
1047 
1048     vnet = user->has_net ? g_strdup(user->net) :
1049            user->has_ip  ? g_strdup_printf("%s/24", user->ip) :
1050            NULL;
1051 
1052     dnssearch = slirp_dnssearch(user->dnssearch);
1053 
1054     /* all optional fields are initialized to "all bits zero" */
1055 
1056     net_init_slirp_configs(user->hostfwd, SLIRP_CFG_HOSTFWD);
1057     net_init_slirp_configs(user->guestfwd, 0);
1058 
1059     ret = net_slirp_init(peer, "user", name, user->q_restrict,
1060                          ipv4, vnet, user->host,
1061                          ipv6, user->ipv6_prefix, user->ipv6_prefixlen,
1062                          user->ipv6_host, user->hostname, user->tftp,
1063                          user->bootfile, user->dhcpstart,
1064                          user->dns, user->ipv6_dns, user->smb,
1065                          user->smbserver, dnssearch, user->domainname,
1066                          user->tftp_server_name, errp);
1067 
1068     while (slirp_configs) {
1069         config = slirp_configs;
1070         slirp_configs = config->next;
1071         g_free(config);
1072     }
1073 
1074     g_free(vnet);
1075     g_free(dnssearch);
1076 
1077     return ret;
1078 }
1079