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