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