xref: /openbmc/qemu/net/slirp.c (revision 835fde4a)
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     NetdevUserOptions *stored;
381     StringList **stored_hostfwd;
382     StringList **stored_guestfwd;
383 
384     if (!ipv4 && (vnetwork || vhost || vnameserver)) {
385         error_setg(errp, "IPv4 disabled but netmask/host/dns provided");
386         return -1;
387     }
388 
389     if (!ipv6 && (vprefix6 || vhost6 || vnameserver6)) {
390         error_setg(errp, "IPv6 disabled but prefix/host6/dns6 provided");
391         return -1;
392     }
393 
394     if (!ipv4 && !ipv6) {
395         /* It doesn't make sense to disable both */
396         error_setg(errp, "IPv4 and IPv6 disabled");
397         return -1;
398     }
399 
400     if (vnetwork) {
401         if (get_str_sep(buf, sizeof(buf), &vnetwork, '/') < 0) {
402             if (!inet_aton(vnetwork, &net)) {
403                 error_setg(errp, "Failed to parse netmask");
404                 return -1;
405             }
406             addr = ntohl(net.s_addr);
407             if (!(addr & 0x80000000)) {
408                 mask.s_addr = htonl(0xff000000); /* class A */
409             } else if ((addr & 0xfff00000) == 0xac100000) {
410                 mask.s_addr = htonl(0xfff00000); /* priv. 172.16.0.0/12 */
411             } else if ((addr & 0xc0000000) == 0x80000000) {
412                 mask.s_addr = htonl(0xffff0000); /* class B */
413             } else if ((addr & 0xffff0000) == 0xc0a80000) {
414                 mask.s_addr = htonl(0xffff0000); /* priv. 192.168.0.0/16 */
415             } else if ((addr & 0xffff0000) == 0xc6120000) {
416                 mask.s_addr = htonl(0xfffe0000); /* tests 198.18.0.0/15 */
417             } else if ((addr & 0xe0000000) == 0xe0000000) {
418                 mask.s_addr = htonl(0xffffff00); /* class C */
419             } else {
420                 mask.s_addr = htonl(0xfffffff0); /* multicast/reserved */
421             }
422         } else {
423             if (!inet_aton(buf, &net)) {
424                 error_setg(errp, "Failed to parse netmask");
425                 return -1;
426             }
427             shift = strtol(vnetwork, &end, 10);
428             if (*end != '\0') {
429                 if (!inet_aton(vnetwork, &mask)) {
430                     error_setg(errp,
431                                "Failed to parse netmask (trailing chars)");
432                     return -1;
433                 }
434             } else if (shift < 4 || shift > 32) {
435                 error_setg(errp,
436                            "Invalid netmask provided (must be in range 4-32)");
437                 return -1;
438             } else {
439                 mask.s_addr = htonl(0xffffffff << (32 - shift));
440             }
441         }
442         net.s_addr &= mask.s_addr;
443         host.s_addr = net.s_addr | (htonl(0x0202) & ~mask.s_addr);
444         dhcp.s_addr = net.s_addr | (htonl(0x020f) & ~mask.s_addr);
445         dns.s_addr  = net.s_addr | (htonl(0x0203) & ~mask.s_addr);
446     }
447 
448     if (vhost && !inet_aton(vhost, &host)) {
449         error_setg(errp, "Failed to parse host");
450         return -1;
451     }
452     if ((host.s_addr & mask.s_addr) != net.s_addr) {
453         error_setg(errp, "Host doesn't belong to network");
454         return -1;
455     }
456 
457     if (vnameserver && !inet_aton(vnameserver, &dns)) {
458         error_setg(errp, "Failed to parse DNS");
459         return -1;
460     }
461     if (restricted && (dns.s_addr & mask.s_addr) != net.s_addr) {
462         error_setg(errp, "DNS doesn't belong to network");
463         return -1;
464     }
465     if (dns.s_addr == host.s_addr) {
466         error_setg(errp, "DNS must be different from host");
467         return -1;
468     }
469 
470     if (vdhcp_start && !inet_aton(vdhcp_start, &dhcp)) {
471         error_setg(errp, "Failed to parse DHCP start address");
472         return -1;
473     }
474     if ((dhcp.s_addr & mask.s_addr) != net.s_addr) {
475         error_setg(errp, "DHCP doesn't belong to network");
476         return -1;
477     }
478     if (dhcp.s_addr == host.s_addr || dhcp.s_addr == dns.s_addr) {
479         error_setg(errp, "DHCP must be different from host and DNS");
480         return -1;
481     }
482 
483 #ifndef _WIN32
484     if (vsmbserver && !inet_aton(vsmbserver, &smbsrv)) {
485         error_setg(errp, "Failed to parse SMB address");
486         return -1;
487     }
488 #endif
489 
490     if (!vprefix6) {
491         vprefix6 = "fec0::";
492     }
493     if (!inet_pton(AF_INET6, vprefix6, &ip6_prefix)) {
494         error_setg(errp, "Failed to parse IPv6 prefix");
495         return -1;
496     }
497 
498     if (!vprefix6_len) {
499         vprefix6_len = 64;
500     }
501     if (vprefix6_len < 0 || vprefix6_len > 126) {
502         error_setg(errp,
503                    "Invalid IPv6 prefix provided "
504                    "(IPv6 prefix length must be between 0 and 126)");
505         return -1;
506     }
507 
508     if (vhost6) {
509         if (!inet_pton(AF_INET6, vhost6, &ip6_host)) {
510             error_setg(errp, "Failed to parse IPv6 host");
511             return -1;
512         }
513         if (!in6_equal_net(&ip6_prefix, &ip6_host, vprefix6_len)) {
514             error_setg(errp, "IPv6 Host doesn't belong to network");
515             return -1;
516         }
517     } else {
518         ip6_host = ip6_prefix;
519         ip6_host.s6_addr[15] |= 2;
520     }
521 
522     if (vnameserver6) {
523         if (!inet_pton(AF_INET6, vnameserver6, &ip6_dns)) {
524             error_setg(errp, "Failed to parse IPv6 DNS");
525             return -1;
526         }
527         if (restricted && !in6_equal_net(&ip6_prefix, &ip6_dns, vprefix6_len)) {
528             error_setg(errp, "IPv6 DNS doesn't belong to network");
529             return -1;
530         }
531     } else {
532         ip6_dns = ip6_prefix;
533         ip6_dns.s6_addr[15] |= 3;
534     }
535 
536     if (vdomainname && !*vdomainname) {
537         error_setg(errp, "'domainname' parameter cannot be empty");
538         return -1;
539     }
540 
541     if (vdomainname && strlen(vdomainname) > 255) {
542         error_setg(errp, "'domainname' parameter cannot exceed 255 bytes");
543         return -1;
544     }
545 
546     if (vhostname && strlen(vhostname) > 255) {
547         error_setg(errp, "'vhostname' parameter cannot exceed 255 bytes");
548         return -1;
549     }
550 
551     if (tftp_server_name && strlen(tftp_server_name) > 255) {
552         error_setg(errp, "'tftp-server-name' parameter cannot exceed 255 bytes");
553         return -1;
554     }
555 
556     nc = qemu_new_net_client(&net_slirp_info, peer, model, name);
557 
558     /* Store startup parameters */
559     nc->stored_config = g_new0(NetdevInfo, 1);
560     nc->stored_config->type = NET_BACKEND_USER;
561     stored = &nc->stored_config->u.user;
562 
563     if (vhostname) {
564         stored->has_hostname = true;
565         stored->hostname = g_strdup(vhostname);
566     }
567 
568     stored->has_q_restrict = true;
569     stored->q_restrict = restricted;
570 
571     stored->has_ipv4 = true;
572     stored->ipv4 = ipv4;
573 
574     stored->has_ipv6 = true;
575     stored->ipv6 = ipv6;
576 
577     if (ipv4) {
578         uint8_t *net_bytes = (uint8_t *)&net;
579         uint8_t *mask_bytes = (uint8_t *)&mask;
580 
581         stored->has_net = true;
582         stored->net = g_strdup_printf("%d.%d.%d.%d/%d.%d.%d.%d",
583                                       net_bytes[0], net_bytes[1],
584                                       net_bytes[2], net_bytes[3],
585                                       mask_bytes[0], mask_bytes[1],
586                                       mask_bytes[2], mask_bytes[3]);
587 
588         stored->has_host = true;
589         stored->host = g_strdup(inet_ntoa(host));
590     }
591 
592     if (tftp_export) {
593         stored->has_tftp = true;
594         stored->tftp = g_strdup(tftp_export);
595     }
596 
597     if (bootfile) {
598         stored->has_bootfile = true;
599         stored->bootfile = g_strdup(bootfile);
600     }
601 
602     if (vdhcp_start) {
603         stored->has_dhcpstart = true;
604         stored->dhcpstart = g_strdup(vdhcp_start);
605     }
606 
607     if (ipv4) {
608         stored->has_dns = true;
609         stored->dns = g_strdup(inet_ntoa(dns));
610     }
611 
612     if (dnssearch) {
613         stored->has_dnssearch = true;
614         StringList **stored_list = &stored->dnssearch;
615 
616         for (int i = 0; dnssearch[i]; i++) {
617             String *element = g_new0(String, 1);
618 
619             element->str = g_strdup(dnssearch[i]);
620             QAPI_LIST_APPEND(stored_list, element);
621         }
622     }
623 
624     if (vdomainname) {
625         stored->has_domainname = true;
626         stored->domainname = g_strdup(vdomainname);
627     }
628 
629     if (ipv6) {
630         char addrstr[INET6_ADDRSTRLEN];
631         const char *res;
632 
633         stored->has_ipv6_prefix = true;
634         stored->ipv6_prefix = g_strdup(vprefix6);
635 
636         stored->has_ipv6_prefixlen = true;
637         stored->ipv6_prefixlen = vprefix6_len;
638 
639         res = inet_ntop(AF_INET6, &ip6_host,
640                         addrstr, sizeof(addrstr));
641 
642         stored->has_ipv6_host = true;
643         stored->ipv6_host = g_strdup(res);
644 
645         res = inet_ntop(AF_INET6, &ip6_dns,
646                         addrstr, sizeof(addrstr));
647 
648         stored->has_ipv6_dns = true;
649         stored->ipv6_dns = g_strdup(res);
650     }
651 
652     if (smb_export) {
653         stored->has_smb = true;
654         stored->smb = g_strdup(smb_export);
655     }
656 
657     if (vsmbserver) {
658         stored->has_smbserver = true;
659         stored->smbserver = g_strdup(vsmbserver);
660     }
661 
662     if (tftp_server_name) {
663         stored->has_tftp_server_name = true;
664         stored->tftp_server_name = g_strdup(tftp_server_name);
665     }
666 
667     s = DO_UPCAST(SlirpState, nc, nc);
668 
669     s->slirp = slirp_init(restricted, ipv4, net, mask, host,
670                           ipv6, ip6_prefix, vprefix6_len, ip6_host,
671                           vhostname, tftp_server_name,
672                           tftp_export, bootfile, dhcp,
673                           dns, ip6_dns, dnssearch, vdomainname,
674                           &slirp_cb, s);
675     QTAILQ_INSERT_TAIL(&slirp_stacks, s, entry);
676 
677     /*
678      * Make sure the current bitstream version of slirp is 4, to avoid
679      * QEMU migration incompatibilities, if upstream slirp bumped the
680      * version.
681      *
682      * FIXME: use bitfields of features? teach libslirp to save with
683      * specific version?
684      */
685     g_assert(slirp_state_version() == 4);
686     register_savevm_live("slirp", 0, slirp_state_version(),
687                          &savevm_slirp_state, s->slirp);
688 
689     s->poll_notifier.notify = net_slirp_poll_notify;
690     main_loop_poll_add_notifier(&s->poll_notifier);
691 
692     stored_hostfwd = &stored->hostfwd;
693     stored_guestfwd = &stored->guestfwd;
694 
695     for (config = slirp_configs; config; config = config->next) {
696         String *element = g_new0(String, 1);
697 
698         element->str = g_strdup(config->str);
699         if (config->flags & SLIRP_CFG_HOSTFWD) {
700             if (slirp_hostfwd(s, config->str, errp) < 0) {
701                 goto error;
702             }
703             stored->has_hostfwd = true;
704             QAPI_LIST_APPEND(stored_hostfwd, element);
705         } else {
706             if (slirp_guestfwd(s, config->str, errp) < 0) {
707                 goto error;
708             }
709             stored->has_guestfwd = true;
710             QAPI_LIST_APPEND(stored_guestfwd, element);
711         }
712     }
713 #ifndef _WIN32
714     if (smb_export) {
715         if (slirp_smb(s, smb_export, smbsrv, errp) < 0) {
716             goto error;
717         }
718     }
719 #endif
720 
721     s->exit_notifier.notify = slirp_smb_exit;
722     qemu_add_exit_notifier(&s->exit_notifier);
723     return 0;
724 
725 error:
726     qemu_del_net_client(nc);
727     return -1;
728 }
729 
730 static SlirpState *slirp_lookup(Monitor *mon, const char *id)
731 {
732     if (id) {
733         NetClientState *nc = qemu_find_netdev(id);
734         if (!nc) {
735             monitor_printf(mon, "unrecognized netdev id '%s'\n", id);
736             return NULL;
737         }
738         if (strcmp(nc->model, "user")) {
739             monitor_printf(mon, "invalid device specified\n");
740             return NULL;
741         }
742         return DO_UPCAST(SlirpState, nc, nc);
743     } else {
744         if (QTAILQ_EMPTY(&slirp_stacks)) {
745             monitor_printf(mon, "user mode network stack not in use\n");
746             return NULL;
747         }
748         return QTAILQ_FIRST(&slirp_stacks);
749     }
750 }
751 
752 void hmp_hostfwd_remove(Monitor *mon, const QDict *qdict)
753 {
754     struct in_addr host_addr = { .s_addr = INADDR_ANY };
755     int host_port;
756     char buf[256];
757     const char *src_str, *p;
758     SlirpState *s;
759     int is_udp = 0;
760     int err;
761     const char *arg1 = qdict_get_str(qdict, "arg1");
762     const char *arg2 = qdict_get_try_str(qdict, "arg2");
763 
764     if (arg2) {
765         s = slirp_lookup(mon, arg1);
766         src_str = arg2;
767     } else {
768         s = slirp_lookup(mon, NULL);
769         src_str = arg1;
770     }
771     if (!s) {
772         return;
773     }
774 
775     p = src_str;
776     if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
777         goto fail_syntax;
778     }
779 
780     if (!strcmp(buf, "tcp") || buf[0] == '\0') {
781         is_udp = 0;
782     } else if (!strcmp(buf, "udp")) {
783         is_udp = 1;
784     } else {
785         goto fail_syntax;
786     }
787 
788     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
789         goto fail_syntax;
790     }
791     if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
792         goto fail_syntax;
793     }
794 
795     if (qemu_strtoi(p, NULL, 10, &host_port)) {
796         goto fail_syntax;
797     }
798 
799     err = slirp_remove_hostfwd(s->slirp, is_udp, host_addr, host_port);
800 
801     monitor_printf(mon, "host forwarding rule for %s %s\n", src_str,
802                    err ? "not found" : "removed");
803     return;
804 
805  fail_syntax:
806     monitor_printf(mon, "invalid format\n");
807 }
808 
809 static int slirp_hostfwd(SlirpState *s, const char *redir_str, Error **errp)
810 {
811     struct in_addr host_addr = { .s_addr = INADDR_ANY };
812     struct in_addr guest_addr = { .s_addr = 0 };
813     int host_port, guest_port;
814     const char *p;
815     char buf[256];
816     int is_udp;
817     char *end;
818     const char *fail_reason = "Unknown reason";
819 
820     p = redir_str;
821     if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
822         fail_reason = "No : separators";
823         goto fail_syntax;
824     }
825     if (!strcmp(buf, "tcp") || buf[0] == '\0') {
826         is_udp = 0;
827     } else if (!strcmp(buf, "udp")) {
828         is_udp = 1;
829     } else {
830         fail_reason = "Bad protocol name";
831         goto fail_syntax;
832     }
833 
834     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
835         fail_reason = "Missing : separator";
836         goto fail_syntax;
837     }
838     if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
839         fail_reason = "Bad host address";
840         goto fail_syntax;
841     }
842 
843     if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {
844         fail_reason = "Bad host port separator";
845         goto fail_syntax;
846     }
847     host_port = strtol(buf, &end, 0);
848     if (*end != '\0' || host_port < 0 || host_port > 65535) {
849         fail_reason = "Bad host port";
850         goto fail_syntax;
851     }
852 
853     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
854         fail_reason = "Missing guest address";
855         goto fail_syntax;
856     }
857     if (buf[0] != '\0' && !inet_aton(buf, &guest_addr)) {
858         fail_reason = "Bad guest address";
859         goto fail_syntax;
860     }
861 
862     guest_port = strtol(p, &end, 0);
863     if (*end != '\0' || guest_port < 1 || guest_port > 65535) {
864         fail_reason = "Bad guest port";
865         goto fail_syntax;
866     }
867 
868     if (slirp_add_hostfwd(s->slirp, is_udp, host_addr, host_port, guest_addr,
869                           guest_port) < 0) {
870         error_setg(errp, "Could not set up host forwarding rule '%s'",
871                    redir_str);
872         return -1;
873     }
874     return 0;
875 
876  fail_syntax:
877     error_setg(errp, "Invalid host forwarding rule '%s' (%s)", redir_str,
878                fail_reason);
879     return -1;
880 }
881 
882 void hmp_hostfwd_add(Monitor *mon, const QDict *qdict)
883 {
884     const char *redir_str;
885     SlirpState *s;
886     const char *arg1 = qdict_get_str(qdict, "arg1");
887     const char *arg2 = qdict_get_try_str(qdict, "arg2");
888 
889     if (arg2) {
890         s = slirp_lookup(mon, arg1);
891         redir_str = arg2;
892     } else {
893         s = slirp_lookup(mon, NULL);
894         redir_str = arg1;
895     }
896     if (s) {
897         Error *err = NULL;
898         if (slirp_hostfwd(s, redir_str, &err) < 0) {
899             error_report_err(err);
900         }
901     }
902 
903 }
904 
905 #ifndef _WIN32
906 
907 /* automatic user mode samba server configuration */
908 static void slirp_smb_cleanup(SlirpState *s)
909 {
910     int ret;
911 
912     if (s->smb_dir) {
913         gchar *cmd = g_strdup_printf("rm -rf %s", s->smb_dir);
914         ret = system(cmd);
915         if (ret == -1 || !WIFEXITED(ret)) {
916             error_report("'%s' failed.", cmd);
917         } else if (WEXITSTATUS(ret)) {
918             error_report("'%s' failed. Error code: %d",
919                          cmd, WEXITSTATUS(ret));
920         }
921         g_free(cmd);
922         g_free(s->smb_dir);
923         s->smb_dir = NULL;
924     }
925 }
926 
927 static int slirp_smb(SlirpState* s, const char *exported_dir,
928                      struct in_addr vserver_addr, Error **errp)
929 {
930     char *smb_conf;
931     char *smb_cmdline;
932     struct passwd *passwd;
933     FILE *f;
934 
935     passwd = getpwuid(geteuid());
936     if (!passwd) {
937         error_setg(errp, "Failed to retrieve user name");
938         return -1;
939     }
940 
941     if (access(CONFIG_SMBD_COMMAND, F_OK)) {
942         error_setg(errp, "Could not find '%s', please install it",
943                    CONFIG_SMBD_COMMAND);
944         return -1;
945     }
946 
947     if (access(exported_dir, R_OK | X_OK)) {
948         error_setg(errp, "Error accessing shared directory '%s': %s",
949                    exported_dir, strerror(errno));
950         return -1;
951     }
952 
953     s->smb_dir = g_dir_make_tmp("qemu-smb.XXXXXX", NULL);
954     if (!s->smb_dir) {
955         error_setg(errp, "Could not create samba server dir");
956         return -1;
957     }
958     smb_conf = g_strdup_printf("%s/%s", s->smb_dir, "smb.conf");
959 
960     f = fopen(smb_conf, "w");
961     if (!f) {
962         slirp_smb_cleanup(s);
963         error_setg(errp,
964                    "Could not create samba server configuration file '%s'",
965                     smb_conf);
966         g_free(smb_conf);
967         return -1;
968     }
969     fprintf(f,
970             "[global]\n"
971             "private dir=%s\n"
972             "interfaces=127.0.0.1\n"
973             "bind interfaces only=yes\n"
974             "pid directory=%s\n"
975             "lock directory=%s\n"
976             "state directory=%s\n"
977             "cache directory=%s\n"
978             "ncalrpc dir=%s/ncalrpc\n"
979             "log file=%s/log.smbd\n"
980             "smb passwd file=%s/smbpasswd\n"
981             "security = user\n"
982             "map to guest = Bad User\n"
983             "load printers = no\n"
984             "printing = bsd\n"
985             "disable spoolss = yes\n"
986             "usershare max shares = 0\n"
987             "[qemu]\n"
988             "path=%s\n"
989             "read only=no\n"
990             "guest ok=yes\n"
991             "force user=%s\n",
992             s->smb_dir,
993             s->smb_dir,
994             s->smb_dir,
995             s->smb_dir,
996             s->smb_dir,
997             s->smb_dir,
998             s->smb_dir,
999             s->smb_dir,
1000             exported_dir,
1001             passwd->pw_name
1002             );
1003     fclose(f);
1004 
1005     smb_cmdline = g_strdup_printf("%s -l %s -s %s",
1006              CONFIG_SMBD_COMMAND, s->smb_dir, smb_conf);
1007     g_free(smb_conf);
1008 
1009     if (slirp_add_exec(s->slirp, smb_cmdline, &vserver_addr, 139) < 0 ||
1010         slirp_add_exec(s->slirp, smb_cmdline, &vserver_addr, 445) < 0) {
1011         slirp_smb_cleanup(s);
1012         g_free(smb_cmdline);
1013         error_setg(errp, "Conflicting/invalid smbserver address");
1014         return -1;
1015     }
1016     g_free(smb_cmdline);
1017     return 0;
1018 }
1019 
1020 #endif /* !defined(_WIN32) */
1021 
1022 static int guestfwd_can_read(void *opaque)
1023 {
1024     struct GuestFwd *fwd = opaque;
1025     return slirp_socket_can_recv(fwd->slirp, fwd->server, fwd->port);
1026 }
1027 
1028 static void guestfwd_read(void *opaque, const uint8_t *buf, int size)
1029 {
1030     struct GuestFwd *fwd = opaque;
1031     slirp_socket_recv(fwd->slirp, fwd->server, fwd->port, buf, size);
1032 }
1033 
1034 static ssize_t guestfwd_write(const void *buf, size_t len, void *chr)
1035 {
1036     return qemu_chr_fe_write_all(chr, buf, len);
1037 }
1038 
1039 static int slirp_guestfwd(SlirpState *s, const char *config_str, Error **errp)
1040 {
1041     /* TODO: IPv6 */
1042     struct in_addr server = { .s_addr = 0 };
1043     struct GuestFwd *fwd;
1044     const char *p;
1045     char buf[128];
1046     char *end;
1047     int port;
1048 
1049     p = config_str;
1050     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1051         goto fail_syntax;
1052     }
1053     if (strcmp(buf, "tcp") && buf[0] != '\0') {
1054         goto fail_syntax;
1055     }
1056     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1057         goto fail_syntax;
1058     }
1059     if (buf[0] != '\0' && !inet_aton(buf, &server)) {
1060         goto fail_syntax;
1061     }
1062     if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {
1063         goto fail_syntax;
1064     }
1065     port = strtol(buf, &end, 10);
1066     if (*end != '\0' || port < 1 || port > 65535) {
1067         goto fail_syntax;
1068     }
1069 
1070     snprintf(buf, sizeof(buf), "guestfwd.tcp.%d", port);
1071 
1072     if (g_str_has_prefix(p, "cmd:")) {
1073         if (slirp_add_exec(s->slirp, &p[4], &server, port) < 0) {
1074             error_setg(errp, "Conflicting/invalid host:port in guest "
1075                        "forwarding rule '%s'", config_str);
1076             return -1;
1077         }
1078     } else {
1079         Error *err = NULL;
1080         /*
1081          * FIXME: sure we want to support implicit
1082          * muxed monitors here?
1083          */
1084         Chardev *chr = qemu_chr_new_mux_mon(buf, p, NULL);
1085 
1086         if (!chr) {
1087             error_setg(errp, "Could not open guest forwarding device '%s'",
1088                        buf);
1089             return -1;
1090         }
1091 
1092         fwd = g_new(struct GuestFwd, 1);
1093         qemu_chr_fe_init(&fwd->hd, chr, &err);
1094         if (err) {
1095             error_propagate(errp, err);
1096             object_unparent(OBJECT(chr));
1097             g_free(fwd);
1098             return -1;
1099         }
1100 
1101         if (slirp_add_guestfwd(s->slirp, guestfwd_write, &fwd->hd,
1102                                &server, port) < 0) {
1103             error_setg(errp, "Conflicting/invalid host:port in guest "
1104                        "forwarding rule '%s'", config_str);
1105             qemu_chr_fe_deinit(&fwd->hd, true);
1106             g_free(fwd);
1107             return -1;
1108         }
1109         fwd->server = server;
1110         fwd->port = port;
1111         fwd->slirp = s->slirp;
1112 
1113         qemu_chr_fe_set_handlers(&fwd->hd, guestfwd_can_read, guestfwd_read,
1114                                  NULL, NULL, fwd, NULL, true);
1115         s->fwd = g_slist_append(s->fwd, fwd);
1116     }
1117     return 0;
1118 
1119  fail_syntax:
1120     error_setg(errp, "Invalid guest forwarding rule '%s'", config_str);
1121     return -1;
1122 }
1123 
1124 void hmp_info_usernet(Monitor *mon, const QDict *qdict)
1125 {
1126     SlirpState *s;
1127 
1128     QTAILQ_FOREACH(s, &slirp_stacks, entry) {
1129         int id;
1130         bool got_hub_id = net_hub_id_for_client(&s->nc, &id) == 0;
1131         char *info = slirp_connection_info(s->slirp);
1132         monitor_printf(mon, "Hub %d (%s):\n%s",
1133                        got_hub_id ? id : -1,
1134                        s->nc.name, info);
1135         g_free(info);
1136     }
1137 }
1138 
1139 static void
1140 net_init_slirp_configs(const StringList *fwd, int flags)
1141 {
1142     while (fwd) {
1143         struct slirp_config_str *config;
1144 
1145         config = g_malloc0(sizeof(*config));
1146         pstrcpy(config->str, sizeof(config->str), fwd->value->str);
1147         config->flags = flags;
1148         config->next = slirp_configs;
1149         slirp_configs = config;
1150 
1151         fwd = fwd->next;
1152     }
1153 }
1154 
1155 static const char **slirp_dnssearch(const StringList *dnsname)
1156 {
1157     const StringList *c = dnsname;
1158     size_t i = 0, num_opts = 0;
1159     const char **ret;
1160 
1161     while (c) {
1162         num_opts++;
1163         c = c->next;
1164     }
1165 
1166     if (num_opts == 0) {
1167         return NULL;
1168     }
1169 
1170     ret = g_malloc((num_opts + 1) * sizeof(*ret));
1171     c = dnsname;
1172     while (c) {
1173         ret[i++] = c->value->str;
1174         c = c->next;
1175     }
1176     ret[i] = NULL;
1177     return ret;
1178 }
1179 
1180 int net_init_slirp(const Netdev *netdev, const char *name,
1181                    NetClientState *peer, Error **errp)
1182 {
1183     struct slirp_config_str *config;
1184     char *vnet;
1185     int ret;
1186     const NetdevUserOptions *user;
1187     const char **dnssearch;
1188     bool ipv4 = true, ipv6 = true;
1189 
1190     assert(netdev->type == NET_CLIENT_DRIVER_USER);
1191     user = &netdev->u.user;
1192 
1193     if ((user->has_ipv6 && user->ipv6 && !user->has_ipv4) ||
1194         (user->has_ipv4 && !user->ipv4)) {
1195         ipv4 = 0;
1196     }
1197     if ((user->has_ipv4 && user->ipv4 && !user->has_ipv6) ||
1198         (user->has_ipv6 && !user->ipv6)) {
1199         ipv6 = 0;
1200     }
1201 
1202     vnet = user->has_net ? g_strdup(user->net) :
1203            user->has_ip  ? g_strdup_printf("%s/24", user->ip) :
1204            NULL;
1205 
1206     dnssearch = slirp_dnssearch(user->dnssearch);
1207 
1208     /* all optional fields are initialized to "all bits zero" */
1209 
1210     net_init_slirp_configs(user->hostfwd, SLIRP_CFG_HOSTFWD);
1211     net_init_slirp_configs(user->guestfwd, 0);
1212 
1213     ret = net_slirp_init(peer, "user", name, user->q_restrict,
1214                          ipv4, vnet, user->host,
1215                          ipv6, user->ipv6_prefix, user->ipv6_prefixlen,
1216                          user->ipv6_host, user->hostname, user->tftp,
1217                          user->bootfile, user->dhcpstart,
1218                          user->dns, user->ipv6_dns, user->smb,
1219                          user->smbserver, dnssearch, user->domainname,
1220                          user->tftp_server_name, errp);
1221 
1222     while (slirp_configs) {
1223         config = slirp_configs;
1224         slirp_configs = config->next;
1225         g_free(config);
1226     }
1227 
1228     g_free(vnet);
1229     g_free(dnssearch);
1230 
1231     return ret;
1232 }
1233