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