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