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