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