xref: /openbmc/qemu/util/qemu-sockets.c (revision 6c35ed68)
1 /*
2  *  inet and unix socket functions for qemu
3  *
4  *  (c) 2008 Gerd Hoffmann <kraxel@redhat.com>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; under version 2 of the License.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  * Contributions after 2012-01-13 are licensed under the terms of the
16  * GNU GPL, version 2 or (at your option) any later version.
17  */
18 #include "qemu/osdep.h"
19 
20 #ifdef CONFIG_AF_VSOCK
21 #include <linux/vm_sockets.h>
22 #endif /* CONFIG_AF_VSOCK */
23 
24 #include "qemu-common.h"
25 #include "monitor/monitor.h"
26 #include "qapi/clone-visitor.h"
27 #include "qapi/error.h"
28 #include "qapi/qapi-visit-sockets.h"
29 #include "qemu/sockets.h"
30 #include "qemu/main-loop.h"
31 #include "qapi/qobject-input-visitor.h"
32 #include "qapi/qobject-output-visitor.h"
33 #include "qemu/cutils.h"
34 #include "trace.h"
35 
36 #ifndef AI_ADDRCONFIG
37 # define AI_ADDRCONFIG 0
38 #endif
39 
40 #ifndef AI_V4MAPPED
41 # define AI_V4MAPPED 0
42 #endif
43 
44 #ifndef AI_NUMERICSERV
45 # define AI_NUMERICSERV 0
46 #endif
47 
48 
49 static int inet_getport(struct addrinfo *e)
50 {
51     struct sockaddr_in *i4;
52     struct sockaddr_in6 *i6;
53 
54     switch (e->ai_family) {
55     case PF_INET6:
56         i6 = (void*)e->ai_addr;
57         return ntohs(i6->sin6_port);
58     case PF_INET:
59         i4 = (void*)e->ai_addr;
60         return ntohs(i4->sin_port);
61     default:
62         return 0;
63     }
64 }
65 
66 static void inet_setport(struct addrinfo *e, int port)
67 {
68     struct sockaddr_in *i4;
69     struct sockaddr_in6 *i6;
70 
71     switch (e->ai_family) {
72     case PF_INET6:
73         i6 = (void*)e->ai_addr;
74         i6->sin6_port = htons(port);
75         break;
76     case PF_INET:
77         i4 = (void*)e->ai_addr;
78         i4->sin_port = htons(port);
79         break;
80     }
81 }
82 
83 NetworkAddressFamily inet_netfamily(int family)
84 {
85     switch (family) {
86     case PF_INET6: return NETWORK_ADDRESS_FAMILY_IPV6;
87     case PF_INET:  return NETWORK_ADDRESS_FAMILY_IPV4;
88     case PF_UNIX:  return NETWORK_ADDRESS_FAMILY_UNIX;
89 #ifdef CONFIG_AF_VSOCK
90     case PF_VSOCK: return NETWORK_ADDRESS_FAMILY_VSOCK;
91 #endif /* CONFIG_AF_VSOCK */
92     }
93     return NETWORK_ADDRESS_FAMILY_UNKNOWN;
94 }
95 
96 bool fd_is_socket(int fd)
97 {
98     int optval;
99     socklen_t optlen = sizeof(optval);
100     return !qemu_getsockopt(fd, SOL_SOCKET, SO_TYPE, &optval, &optlen);
101 }
102 
103 
104 /*
105  * Matrix we're trying to apply
106  *
107  *  ipv4  ipv6   family
108  *   -     -       PF_UNSPEC
109  *   -     f       PF_INET
110  *   -     t       PF_INET6
111  *   f     -       PF_INET6
112  *   f     f       <error>
113  *   f     t       PF_INET6
114  *   t     -       PF_INET
115  *   t     f       PF_INET
116  *   t     t       PF_INET6/PF_UNSPEC
117  *
118  * NB, this matrix is only about getting the necessary results
119  * from getaddrinfo(). Some of the cases require further work
120  * after reading results from getaddrinfo in order to fully
121  * apply the logic the end user wants.
122  *
123  * In the first and last cases, we must set IPV6_V6ONLY=0
124  * when binding, to allow a single listener to potentially
125  * accept both IPv4+6 addresses.
126  */
127 int inet_ai_family_from_address(InetSocketAddress *addr,
128                                 Error **errp)
129 {
130     if (addr->has_ipv6 && addr->has_ipv4 &&
131         !addr->ipv6 && !addr->ipv4) {
132         error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
133         return PF_UNSPEC;
134     }
135     if ((addr->has_ipv6 && addr->ipv6) && (addr->has_ipv4 && addr->ipv4)) {
136         /*
137          * Some backends can only do a single listener. In that case
138          * we want empty hostname to resolve to "::" and then use the
139          * flag IPV6_V6ONLY==0 to get both protocols on 1 socket. This
140          * doesn't work for addresses other than "", so they're just
141          * inevitably broken until multiple listeners can be used,
142          * and thus we honour getaddrinfo automatic protocol detection
143          * Once all backends do multi-listener, remove the PF_INET6
144          * branch entirely.
145          */
146         if (!addr->host || g_str_equal(addr->host, "")) {
147             return PF_INET6;
148         } else {
149             return PF_UNSPEC;
150         }
151     }
152     if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
153         return PF_INET6;
154     }
155     if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
156         return PF_INET;
157     }
158     return PF_UNSPEC;
159 }
160 
161 static int create_fast_reuse_socket(struct addrinfo *e)
162 {
163     int slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
164     if (slisten < 0) {
165         return -1;
166     }
167     socket_set_fast_reuse(slisten);
168     return slisten;
169 }
170 
171 static int try_bind(int socket, InetSocketAddress *saddr, struct addrinfo *e)
172 {
173 #ifndef IPV6_V6ONLY
174     return bind(socket, e->ai_addr, e->ai_addrlen);
175 #else
176     /*
177      * Deals with first & last cases in matrix in comment
178      * for inet_ai_family_from_address().
179      */
180     int v6only =
181         ((!saddr->has_ipv4 && !saddr->has_ipv6) ||
182          (saddr->has_ipv4 && saddr->ipv4 &&
183           saddr->has_ipv6 && saddr->ipv6)) ? 0 : 1;
184     int stat;
185 
186  rebind:
187     if (e->ai_family == PF_INET6) {
188         qemu_setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, &v6only,
189                         sizeof(v6only));
190     }
191 
192     stat = bind(socket, e->ai_addr, e->ai_addrlen);
193     if (!stat) {
194         return 0;
195     }
196 
197     /* If we got EADDRINUSE from an IPv6 bind & v6only is unset,
198      * it could be that the IPv4 port is already claimed, so retry
199      * with v6only set
200      */
201     if (e->ai_family == PF_INET6 && errno == EADDRINUSE && !v6only) {
202         v6only = 1;
203         goto rebind;
204     }
205     return stat;
206 #endif
207 }
208 
209 static int inet_listen_saddr(InetSocketAddress *saddr,
210                              int port_offset,
211                              int num,
212                              Error **errp)
213 {
214     struct addrinfo ai,*res,*e;
215     char port[33];
216     char uaddr[INET6_ADDRSTRLEN+1];
217     char uport[33];
218     int rc, port_min, port_max, p;
219     int slisten = -1;
220     int saved_errno = 0;
221     bool socket_created = false;
222     Error *err = NULL;
223 
224     if (saddr->keep_alive) {
225         error_setg(errp, "keep-alive option is not supported for passive "
226                    "sockets");
227         return -1;
228     }
229 
230     memset(&ai,0, sizeof(ai));
231     ai.ai_flags = AI_PASSIVE;
232     if (saddr->has_numeric && saddr->numeric) {
233         ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
234     }
235     ai.ai_family = inet_ai_family_from_address(saddr, &err);
236     ai.ai_socktype = SOCK_STREAM;
237 
238     if (err) {
239         error_propagate(errp, err);
240         return -1;
241     }
242 
243     if (saddr->host == NULL) {
244         error_setg(errp, "host not specified");
245         return -1;
246     }
247     if (saddr->port != NULL) {
248         pstrcpy(port, sizeof(port), saddr->port);
249     } else {
250         port[0] = '\0';
251     }
252 
253     /* lookup */
254     if (port_offset) {
255         unsigned long long baseport;
256         if (strlen(port) == 0) {
257             error_setg(errp, "port not specified");
258             return -1;
259         }
260         if (parse_uint_full(port, &baseport, 10) < 0) {
261             error_setg(errp, "can't convert to a number: %s", port);
262             return -1;
263         }
264         if (baseport > 65535 ||
265             baseport + port_offset > 65535) {
266             error_setg(errp, "port %s out of range", port);
267             return -1;
268         }
269         snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
270     }
271     rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
272                      strlen(port) ? port : NULL, &ai, &res);
273     if (rc != 0) {
274         error_setg(errp, "address resolution failed for %s:%s: %s",
275                    saddr->host, port, gai_strerror(rc));
276         return -1;
277     }
278 
279     /* create socket + bind/listen */
280     for (e = res; e != NULL; e = e->ai_next) {
281         getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
282                         uaddr,INET6_ADDRSTRLEN,uport,32,
283                         NI_NUMERICHOST | NI_NUMERICSERV);
284 
285         port_min = inet_getport(e);
286         port_max = saddr->has_to ? saddr->to + port_offset : port_min;
287         for (p = port_min; p <= port_max; p++) {
288             inet_setport(e, p);
289 
290             slisten = create_fast_reuse_socket(e);
291             if (slisten < 0) {
292                 /* First time we expect we might fail to create the socket
293                  * eg if 'e' has AF_INET6 but ipv6 kmod is not loaded.
294                  * Later iterations should always succeed if first iteration
295                  * worked though, so treat that as fatal.
296                  */
297                 if (p == port_min) {
298                     continue;
299                 } else {
300                     error_setg_errno(errp, errno,
301                                      "Failed to recreate failed listening socket");
302                     goto listen_failed;
303                 }
304             }
305             socket_created = true;
306 
307             rc = try_bind(slisten, saddr, e);
308             if (rc < 0) {
309                 if (errno != EADDRINUSE) {
310                     error_setg_errno(errp, errno, "Failed to bind socket");
311                     goto listen_failed;
312                 }
313             } else {
314                 if (!listen(slisten, num)) {
315                     goto listen_ok;
316                 }
317                 if (errno != EADDRINUSE) {
318                     error_setg_errno(errp, errno, "Failed to listen on socket");
319                     goto listen_failed;
320                 }
321             }
322             /* Someone else managed to bind to the same port and beat us
323              * to listen on it! Socket semantics does not allow us to
324              * recover from this situation, so we need to recreate the
325              * socket to allow bind attempts for subsequent ports:
326              */
327             closesocket(slisten);
328             slisten = -1;
329         }
330     }
331     error_setg_errno(errp, errno,
332                      socket_created ?
333                      "Failed to find an available port" :
334                      "Failed to create a socket");
335 listen_failed:
336     saved_errno = errno;
337     if (slisten >= 0) {
338         closesocket(slisten);
339     }
340     freeaddrinfo(res);
341     errno = saved_errno;
342     return -1;
343 
344 listen_ok:
345     freeaddrinfo(res);
346     return slisten;
347 }
348 
349 #ifdef _WIN32
350 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
351     ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
352 #else
353 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
354     ((rc) == -EINPROGRESS)
355 #endif
356 
357 static int inet_connect_addr(struct addrinfo *addr, Error **errp);
358 
359 static int inet_connect_addr(struct addrinfo *addr, Error **errp)
360 {
361     int sock, rc;
362 
363     sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
364     if (sock < 0) {
365         error_setg_errno(errp, errno, "Failed to create socket");
366         return -1;
367     }
368     socket_set_fast_reuse(sock);
369 
370     /* connect to peer */
371     do {
372         rc = 0;
373         if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
374             rc = -errno;
375         }
376     } while (rc == -EINTR);
377 
378     if (rc < 0) {
379         error_setg_errno(errp, errno, "Failed to connect socket");
380         closesocket(sock);
381         return -1;
382     }
383 
384     return sock;
385 }
386 
387 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
388                                                  Error **errp)
389 {
390     struct addrinfo ai, *res;
391     int rc;
392     Error *err = NULL;
393     static int useV4Mapped = 1;
394 
395     memset(&ai, 0, sizeof(ai));
396 
397     ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
398     if (atomic_read(&useV4Mapped)) {
399         ai.ai_flags |= AI_V4MAPPED;
400     }
401     ai.ai_family = inet_ai_family_from_address(saddr, &err);
402     ai.ai_socktype = SOCK_STREAM;
403 
404     if (err) {
405         error_propagate(errp, err);
406         return NULL;
407     }
408 
409     if (saddr->host == NULL || saddr->port == NULL) {
410         error_setg(errp, "host and/or port not specified");
411         return NULL;
412     }
413 
414     /* lookup */
415     rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
416 
417     /* At least FreeBSD and OS-X 10.6 declare AI_V4MAPPED but
418      * then don't implement it in their getaddrinfo(). Detect
419      * this and retry without the flag since that's preferrable
420      * to a fatal error
421      */
422     if (rc == EAI_BADFLAGS &&
423         (ai.ai_flags & AI_V4MAPPED)) {
424         atomic_set(&useV4Mapped, 0);
425         ai.ai_flags &= ~AI_V4MAPPED;
426         rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
427     }
428     if (rc != 0) {
429         error_setg(errp, "address resolution failed for %s:%s: %s",
430                    saddr->host, saddr->port, gai_strerror(rc));
431         return NULL;
432     }
433     return res;
434 }
435 
436 /**
437  * Create a socket and connect it to an address.
438  *
439  * @saddr: Inet socket address specification
440  * @errp: set on error
441  *
442  * Returns: -1 on error, file descriptor on success.
443  */
444 int inet_connect_saddr(InetSocketAddress *saddr, Error **errp)
445 {
446     Error *local_err = NULL;
447     struct addrinfo *res, *e;
448     int sock = -1;
449 
450     res = inet_parse_connect_saddr(saddr, errp);
451     if (!res) {
452         return -1;
453     }
454 
455     for (e = res; e != NULL; e = e->ai_next) {
456         error_free(local_err);
457         local_err = NULL;
458         sock = inet_connect_addr(e, &local_err);
459         if (sock >= 0) {
460             break;
461         }
462     }
463 
464     freeaddrinfo(res);
465 
466     if (sock < 0) {
467         error_propagate(errp, local_err);
468         return sock;
469     }
470 
471     if (saddr->keep_alive) {
472         int val = 1;
473         int ret = qemu_setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE,
474                                   &val, sizeof(val));
475 
476         if (ret < 0) {
477             error_setg_errno(errp, errno, "Unable to set KEEPALIVE");
478             close(sock);
479             return -1;
480         }
481     }
482 
483     return sock;
484 }
485 
486 static int inet_dgram_saddr(InetSocketAddress *sraddr,
487                             InetSocketAddress *sladdr,
488                             Error **errp)
489 {
490     struct addrinfo ai, *peer = NULL, *local = NULL;
491     const char *addr;
492     const char *port;
493     int sock = -1, rc;
494     Error *err = NULL;
495 
496     /* lookup peer addr */
497     memset(&ai,0, sizeof(ai));
498     ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
499     ai.ai_family = inet_ai_family_from_address(sraddr, &err);
500     ai.ai_socktype = SOCK_DGRAM;
501 
502     if (err) {
503         error_propagate(errp, err);
504         goto err;
505     }
506 
507     addr = sraddr->host;
508     port = sraddr->port;
509     if (addr == NULL || strlen(addr) == 0) {
510         addr = "localhost";
511     }
512     if (port == NULL || strlen(port) == 0) {
513         error_setg(errp, "remote port not specified");
514         goto err;
515     }
516 
517     if ((rc = getaddrinfo(addr, port, &ai, &peer)) != 0) {
518         error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
519                    gai_strerror(rc));
520         goto err;
521     }
522 
523     /* lookup local addr */
524     memset(&ai,0, sizeof(ai));
525     ai.ai_flags = AI_PASSIVE;
526     ai.ai_family = peer->ai_family;
527     ai.ai_socktype = SOCK_DGRAM;
528 
529     if (sladdr) {
530         addr = sladdr->host;
531         port = sladdr->port;
532         if (addr == NULL || strlen(addr) == 0) {
533             addr = NULL;
534         }
535         if (!port || strlen(port) == 0) {
536             port = "0";
537         }
538     } else {
539         addr = NULL;
540         port = "0";
541     }
542 
543     if ((rc = getaddrinfo(addr, port, &ai, &local)) != 0) {
544         error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
545                    gai_strerror(rc));
546         goto err;
547     }
548 
549     /* create socket */
550     sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
551     if (sock < 0) {
552         error_setg_errno(errp, errno, "Failed to create socket");
553         goto err;
554     }
555     socket_set_fast_reuse(sock);
556 
557     /* bind socket */
558     if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
559         error_setg_errno(errp, errno, "Failed to bind socket");
560         goto err;
561     }
562 
563     /* connect to peer */
564     if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
565         error_setg_errno(errp, errno, "Failed to connect socket");
566         goto err;
567     }
568 
569     freeaddrinfo(local);
570     freeaddrinfo(peer);
571     return sock;
572 
573 err:
574     if (sock != -1) {
575         closesocket(sock);
576     }
577     if (local) {
578         freeaddrinfo(local);
579     }
580     if (peer) {
581         freeaddrinfo(peer);
582     }
583 
584     return -1;
585 }
586 
587 /* compatibility wrapper */
588 static int inet_parse_flag(const char *flagname, const char *optstr, bool *val,
589                            Error **errp)
590 {
591     char *end;
592     size_t len;
593 
594     end = strstr(optstr, ",");
595     if (end) {
596         if (end[1] == ',') { /* Reject 'ipv6=on,,foo' */
597             error_setg(errp, "error parsing '%s' flag '%s'", flagname, optstr);
598             return -1;
599         }
600         len = end - optstr;
601     } else {
602         len = strlen(optstr);
603     }
604     if (len == 0 || (len == 3 && strncmp(optstr, "=on", len) == 0)) {
605         *val = true;
606     } else if (len == 4 && strncmp(optstr, "=off", len) == 0) {
607         *val = false;
608     } else {
609         error_setg(errp, "error parsing '%s' flag '%s'", flagname, optstr);
610         return -1;
611     }
612     return 0;
613 }
614 
615 int inet_parse(InetSocketAddress *addr, const char *str, Error **errp)
616 {
617     const char *optstr, *h;
618     char host[65];
619     char port[33];
620     int to;
621     int pos;
622     char *begin;
623 
624     memset(addr, 0, sizeof(*addr));
625 
626     /* parse address */
627     if (str[0] == ':') {
628         /* no host given */
629         host[0] = '\0';
630         if (sscanf(str, ":%32[^,]%n", port, &pos) != 1) {
631             error_setg(errp, "error parsing port in address '%s'", str);
632             return -1;
633         }
634     } else if (str[0] == '[') {
635         /* IPv6 addr */
636         if (sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos) != 2) {
637             error_setg(errp, "error parsing IPv6 address '%s'", str);
638             return -1;
639         }
640     } else {
641         /* hostname or IPv4 addr */
642         if (sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos) != 2) {
643             error_setg(errp, "error parsing address '%s'", str);
644             return -1;
645         }
646     }
647 
648     addr->host = g_strdup(host);
649     addr->port = g_strdup(port);
650 
651     /* parse options */
652     optstr = str + pos;
653     h = strstr(optstr, ",to=");
654     if (h) {
655         h += 4;
656         if (sscanf(h, "%d%n", &to, &pos) != 1 ||
657             (h[pos] != '\0' && h[pos] != ',')) {
658             error_setg(errp, "error parsing to= argument");
659             return -1;
660         }
661         addr->has_to = true;
662         addr->to = to;
663     }
664     begin = strstr(optstr, ",ipv4");
665     if (begin) {
666         if (inet_parse_flag("ipv4", begin + 5, &addr->ipv4, errp) < 0) {
667             return -1;
668         }
669         addr->has_ipv4 = true;
670     }
671     begin = strstr(optstr, ",ipv6");
672     if (begin) {
673         if (inet_parse_flag("ipv6", begin + 5, &addr->ipv6, errp) < 0) {
674             return -1;
675         }
676         addr->has_ipv6 = true;
677     }
678     begin = strstr(optstr, ",keep-alive");
679     if (begin) {
680         if (inet_parse_flag("keep-alive", begin + strlen(",keep-alive"),
681                             &addr->keep_alive, errp) < 0)
682         {
683             return -1;
684         }
685         addr->has_keep_alive = true;
686     }
687     return 0;
688 }
689 
690 
691 /**
692  * Create a blocking socket and connect it to an address.
693  *
694  * @str: address string
695  * @errp: set in case of an error
696  *
697  * Returns -1 in case of error, file descriptor on success
698  **/
699 int inet_connect(const char *str, Error **errp)
700 {
701     int sock = -1;
702     InetSocketAddress *addr = g_new(InetSocketAddress, 1);
703 
704     if (!inet_parse(addr, str, errp)) {
705         sock = inet_connect_saddr(addr, errp);
706     }
707     qapi_free_InetSocketAddress(addr);
708     return sock;
709 }
710 
711 #ifdef CONFIG_AF_VSOCK
712 static bool vsock_parse_vaddr_to_sockaddr(const VsockSocketAddress *vaddr,
713                                           struct sockaddr_vm *svm,
714                                           Error **errp)
715 {
716     unsigned long long val;
717 
718     memset(svm, 0, sizeof(*svm));
719     svm->svm_family = AF_VSOCK;
720 
721     if (parse_uint_full(vaddr->cid, &val, 10) < 0 ||
722         val > UINT32_MAX) {
723         error_setg(errp, "Failed to parse cid '%s'", vaddr->cid);
724         return false;
725     }
726     svm->svm_cid = val;
727 
728     if (parse_uint_full(vaddr->port, &val, 10) < 0 ||
729         val > UINT32_MAX) {
730         error_setg(errp, "Failed to parse port '%s'", vaddr->port);
731         return false;
732     }
733     svm->svm_port = val;
734 
735     return true;
736 }
737 
738 static int vsock_connect_addr(const struct sockaddr_vm *svm, Error **errp)
739 {
740     int sock, rc;
741 
742     sock = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
743     if (sock < 0) {
744         error_setg_errno(errp, errno, "Failed to create socket");
745         return -1;
746     }
747 
748     /* connect to peer */
749     do {
750         rc = 0;
751         if (connect(sock, (const struct sockaddr *)svm, sizeof(*svm)) < 0) {
752             rc = -errno;
753         }
754     } while (rc == -EINTR);
755 
756     if (rc < 0) {
757         error_setg_errno(errp, errno, "Failed to connect socket");
758         closesocket(sock);
759         return -1;
760     }
761 
762     return sock;
763 }
764 
765 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
766 {
767     struct sockaddr_vm svm;
768     int sock = -1;
769 
770     if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
771         return -1;
772     }
773 
774     sock = vsock_connect_addr(&svm, errp);
775 
776     return sock;
777 }
778 
779 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
780                               int num,
781                               Error **errp)
782 {
783     struct sockaddr_vm svm;
784     int slisten;
785 
786     if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
787         return -1;
788     }
789 
790     slisten = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
791     if (slisten < 0) {
792         error_setg_errno(errp, errno, "Failed to create socket");
793         return -1;
794     }
795 
796     if (bind(slisten, (const struct sockaddr *)&svm, sizeof(svm)) != 0) {
797         error_setg_errno(errp, errno, "Failed to bind socket");
798         closesocket(slisten);
799         return -1;
800     }
801 
802     if (listen(slisten, num) != 0) {
803         error_setg_errno(errp, errno, "Failed to listen on socket");
804         closesocket(slisten);
805         return -1;
806     }
807     return slisten;
808 }
809 
810 static int vsock_parse(VsockSocketAddress *addr, const char *str,
811                        Error **errp)
812 {
813     char cid[33];
814     char port[33];
815     int n;
816 
817     if (sscanf(str, "%32[^:]:%32[^,]%n", cid, port, &n) != 2) {
818         error_setg(errp, "error parsing address '%s'", str);
819         return -1;
820     }
821     if (str[n] != '\0') {
822         error_setg(errp, "trailing characters in address '%s'", str);
823         return -1;
824     }
825 
826     addr->cid = g_strdup(cid);
827     addr->port = g_strdup(port);
828     return 0;
829 }
830 #else
831 static void vsock_unsupported(Error **errp)
832 {
833     error_setg(errp, "socket family AF_VSOCK unsupported");
834 }
835 
836 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
837 {
838     vsock_unsupported(errp);
839     return -1;
840 }
841 
842 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
843                               int num,
844                               Error **errp)
845 {
846     vsock_unsupported(errp);
847     return -1;
848 }
849 
850 static int vsock_parse(VsockSocketAddress *addr, const char *str,
851                         Error **errp)
852 {
853     vsock_unsupported(errp);
854     return -1;
855 }
856 #endif /* CONFIG_AF_VSOCK */
857 
858 #ifndef _WIN32
859 
860 static int unix_listen_saddr(UnixSocketAddress *saddr,
861                              int num,
862                              Error **errp)
863 {
864     struct sockaddr_un un;
865     int sock, fd;
866     char *pathbuf = NULL;
867     const char *path;
868     size_t pathlen;
869 
870     sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
871     if (sock < 0) {
872         error_setg_errno(errp, errno, "Failed to create Unix socket");
873         return -1;
874     }
875 
876     if (saddr->path && saddr->path[0]) {
877         path = saddr->path;
878     } else {
879         const char *tmpdir = getenv("TMPDIR");
880         tmpdir = tmpdir ? tmpdir : "/tmp";
881         path = pathbuf = g_strdup_printf("%s/qemu-socket-XXXXXX", tmpdir);
882     }
883 
884     pathlen = strlen(path);
885     if (pathlen > sizeof(un.sun_path)) {
886         error_setg(errp, "UNIX socket path '%s' is too long", path);
887         error_append_hint(errp, "Path must be less than %zu bytes\n",
888                           sizeof(un.sun_path));
889         goto err;
890     }
891 
892     if (pathbuf != NULL) {
893         /*
894          * This dummy fd usage silences the mktemp() unsecure warning.
895          * Using mkstemp() doesn't make things more secure here
896          * though.  bind() complains about existing files, so we have
897          * to unlink first and thus re-open the race window.  The
898          * worst case possible is bind() failing, i.e. a DoS attack.
899          */
900         fd = mkstemp(pathbuf);
901         if (fd < 0) {
902             error_setg_errno(errp, errno,
903                              "Failed to make a temporary socket %s", pathbuf);
904             goto err;
905         }
906         close(fd);
907     }
908 
909     if (unlink(path) < 0 && errno != ENOENT) {
910         error_setg_errno(errp, errno,
911                          "Failed to unlink socket %s", path);
912         goto err;
913     }
914 
915     memset(&un, 0, sizeof(un));
916     un.sun_family = AF_UNIX;
917     memcpy(un.sun_path, path, pathlen);
918 
919     if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
920         error_setg_errno(errp, errno, "Failed to bind socket to %s", path);
921         goto err;
922     }
923     if (listen(sock, num) < 0) {
924         error_setg_errno(errp, errno, "Failed to listen on socket");
925         goto err;
926     }
927 
928     g_free(pathbuf);
929     return sock;
930 
931 err:
932     g_free(pathbuf);
933     closesocket(sock);
934     return -1;
935 }
936 
937 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
938 {
939     struct sockaddr_un un;
940     int sock, rc;
941     size_t pathlen;
942 
943     if (saddr->path == NULL) {
944         error_setg(errp, "unix connect: no path specified");
945         return -1;
946     }
947 
948     sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
949     if (sock < 0) {
950         error_setg_errno(errp, errno, "Failed to create socket");
951         return -1;
952     }
953 
954     pathlen = strlen(saddr->path);
955     if (pathlen > sizeof(un.sun_path)) {
956         error_setg(errp, "UNIX socket path '%s' is too long", saddr->path);
957         error_append_hint(errp, "Path must be less than %zu bytes\n",
958                           sizeof(un.sun_path));
959         goto err;
960     }
961 
962     memset(&un, 0, sizeof(un));
963     un.sun_family = AF_UNIX;
964     memcpy(un.sun_path, saddr->path, pathlen);
965 
966     /* connect to peer */
967     do {
968         rc = 0;
969         if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
970             rc = -errno;
971         }
972     } while (rc == -EINTR);
973 
974     if (rc < 0) {
975         error_setg_errno(errp, -rc, "Failed to connect socket %s",
976                          saddr->path);
977         goto err;
978     }
979 
980     return sock;
981 
982  err:
983     close(sock);
984     return -1;
985 }
986 
987 #else
988 
989 static int unix_listen_saddr(UnixSocketAddress *saddr,
990                              int num,
991                              Error **errp)
992 {
993     error_setg(errp, "unix sockets are not available on windows");
994     errno = ENOTSUP;
995     return -1;
996 }
997 
998 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
999 {
1000     error_setg(errp, "unix sockets are not available on windows");
1001     errno = ENOTSUP;
1002     return -1;
1003 }
1004 #endif
1005 
1006 /* compatibility wrapper */
1007 int unix_listen(const char *str, Error **errp)
1008 {
1009     UnixSocketAddress *saddr;
1010     int sock;
1011 
1012     saddr = g_new0(UnixSocketAddress, 1);
1013     saddr->path = g_strdup(str);
1014     sock = unix_listen_saddr(saddr, 1, errp);
1015     qapi_free_UnixSocketAddress(saddr);
1016     return sock;
1017 }
1018 
1019 int unix_connect(const char *path, Error **errp)
1020 {
1021     UnixSocketAddress *saddr;
1022     int sock;
1023 
1024     saddr = g_new0(UnixSocketAddress, 1);
1025     saddr->path = g_strdup(path);
1026     sock = unix_connect_saddr(saddr, errp);
1027     qapi_free_UnixSocketAddress(saddr);
1028     return sock;
1029 }
1030 
1031 
1032 SocketAddress *socket_parse(const char *str, Error **errp)
1033 {
1034     SocketAddress *addr;
1035 
1036     addr = g_new0(SocketAddress, 1);
1037     if (strstart(str, "unix:", NULL)) {
1038         if (str[5] == '\0') {
1039             error_setg(errp, "invalid Unix socket address");
1040             goto fail;
1041         } else {
1042             addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1043             addr->u.q_unix.path = g_strdup(str + 5);
1044         }
1045     } else if (strstart(str, "fd:", NULL)) {
1046         if (str[3] == '\0') {
1047             error_setg(errp, "invalid file descriptor address");
1048             goto fail;
1049         } else {
1050             addr->type = SOCKET_ADDRESS_TYPE_FD;
1051             addr->u.fd.str = g_strdup(str + 3);
1052         }
1053     } else if (strstart(str, "vsock:", NULL)) {
1054         addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1055         if (vsock_parse(&addr->u.vsock, str + strlen("vsock:"), errp)) {
1056             goto fail;
1057         }
1058     } else {
1059         addr->type = SOCKET_ADDRESS_TYPE_INET;
1060         if (inet_parse(&addr->u.inet, str, errp)) {
1061             goto fail;
1062         }
1063     }
1064     return addr;
1065 
1066 fail:
1067     qapi_free_SocketAddress(addr);
1068     return NULL;
1069 }
1070 
1071 static int socket_get_fd(const char *fdstr, int num, Error **errp)
1072 {
1073     int fd;
1074     if (num != 1) {
1075         error_setg_errno(errp, EINVAL, "socket_get_fd: too many connections");
1076         return -1;
1077     }
1078     if (cur_mon) {
1079         fd = monitor_get_fd(cur_mon, fdstr, errp);
1080         if (fd < 0) {
1081             return -1;
1082         }
1083     } else {
1084         if (qemu_strtoi(fdstr, NULL, 10, &fd) < 0) {
1085             error_setg_errno(errp, errno,
1086                              "Unable to parse FD number %s",
1087                              fdstr);
1088             return -1;
1089         }
1090     }
1091     if (!fd_is_socket(fd)) {
1092         error_setg(errp, "File descriptor '%s' is not a socket", fdstr);
1093         close(fd);
1094         return -1;
1095     }
1096     return fd;
1097 }
1098 
1099 int socket_connect(SocketAddress *addr, Error **errp)
1100 {
1101     int fd;
1102 
1103     switch (addr->type) {
1104     case SOCKET_ADDRESS_TYPE_INET:
1105         fd = inet_connect_saddr(&addr->u.inet, errp);
1106         break;
1107 
1108     case SOCKET_ADDRESS_TYPE_UNIX:
1109         fd = unix_connect_saddr(&addr->u.q_unix, errp);
1110         break;
1111 
1112     case SOCKET_ADDRESS_TYPE_FD:
1113         fd = socket_get_fd(addr->u.fd.str, 1, errp);
1114         break;
1115 
1116     case SOCKET_ADDRESS_TYPE_VSOCK:
1117         fd = vsock_connect_saddr(&addr->u.vsock, errp);
1118         break;
1119 
1120     default:
1121         abort();
1122     }
1123     return fd;
1124 }
1125 
1126 int socket_listen(SocketAddress *addr, int num, Error **errp)
1127 {
1128     int fd;
1129 
1130     trace_socket_listen(num);
1131     switch (addr->type) {
1132     case SOCKET_ADDRESS_TYPE_INET:
1133         fd = inet_listen_saddr(&addr->u.inet, 0, num, errp);
1134         break;
1135 
1136     case SOCKET_ADDRESS_TYPE_UNIX:
1137         fd = unix_listen_saddr(&addr->u.q_unix, num, errp);
1138         break;
1139 
1140     case SOCKET_ADDRESS_TYPE_FD:
1141         fd = socket_get_fd(addr->u.fd.str, num, errp);
1142         break;
1143 
1144     case SOCKET_ADDRESS_TYPE_VSOCK:
1145         fd = vsock_listen_saddr(&addr->u.vsock, num, errp);
1146         break;
1147 
1148     default:
1149         abort();
1150     }
1151     return fd;
1152 }
1153 
1154 void socket_listen_cleanup(int fd, Error **errp)
1155 {
1156     SocketAddress *addr;
1157 
1158     addr = socket_local_address(fd, errp);
1159     if (!addr) {
1160         return;
1161     }
1162 
1163     if (addr->type == SOCKET_ADDRESS_TYPE_UNIX
1164         && addr->u.q_unix.path) {
1165         if (unlink(addr->u.q_unix.path) < 0 && errno != ENOENT) {
1166             error_setg_errno(errp, errno,
1167                              "Failed to unlink socket %s",
1168                              addr->u.q_unix.path);
1169         }
1170     }
1171 
1172     qapi_free_SocketAddress(addr);
1173 }
1174 
1175 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
1176 {
1177     int fd;
1178 
1179     /*
1180      * TODO SOCKET_ADDRESS_TYPE_FD when fd is AF_INET or AF_INET6
1181      * (although other address families can do SOCK_DGRAM, too)
1182      */
1183     switch (remote->type) {
1184     case SOCKET_ADDRESS_TYPE_INET:
1185         fd = inet_dgram_saddr(&remote->u.inet,
1186                               local ? &local->u.inet : NULL, errp);
1187         break;
1188 
1189     default:
1190         error_setg(errp, "socket type unsupported for datagram");
1191         fd = -1;
1192     }
1193     return fd;
1194 }
1195 
1196 
1197 static SocketAddress *
1198 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1199                                 socklen_t salen,
1200                                 Error **errp)
1201 {
1202     char host[NI_MAXHOST];
1203     char serv[NI_MAXSERV];
1204     SocketAddress *addr;
1205     InetSocketAddress *inet;
1206     int ret;
1207 
1208     ret = getnameinfo((struct sockaddr *)sa, salen,
1209                       host, sizeof(host),
1210                       serv, sizeof(serv),
1211                       NI_NUMERICHOST | NI_NUMERICSERV);
1212     if (ret != 0) {
1213         error_setg(errp, "Cannot format numeric socket address: %s",
1214                    gai_strerror(ret));
1215         return NULL;
1216     }
1217 
1218     addr = g_new0(SocketAddress, 1);
1219     addr->type = SOCKET_ADDRESS_TYPE_INET;
1220     inet = &addr->u.inet;
1221     inet->host = g_strdup(host);
1222     inet->port = g_strdup(serv);
1223     if (sa->ss_family == AF_INET) {
1224         inet->has_ipv4 = inet->ipv4 = true;
1225     } else {
1226         inet->has_ipv6 = inet->ipv6 = true;
1227     }
1228 
1229     return addr;
1230 }
1231 
1232 
1233 #ifndef WIN32
1234 static SocketAddress *
1235 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1236                                 socklen_t salen,
1237                                 Error **errp)
1238 {
1239     SocketAddress *addr;
1240     struct sockaddr_un *su = (struct sockaddr_un *)sa;
1241 
1242     addr = g_new0(SocketAddress, 1);
1243     addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1244     if (su->sun_path[0]) {
1245         addr->u.q_unix.path = g_strndup(su->sun_path, sizeof(su->sun_path));
1246     }
1247 
1248     return addr;
1249 }
1250 #endif /* WIN32 */
1251 
1252 #ifdef CONFIG_AF_VSOCK
1253 static SocketAddress *
1254 socket_sockaddr_to_address_vsock(struct sockaddr_storage *sa,
1255                                  socklen_t salen,
1256                                  Error **errp)
1257 {
1258     SocketAddress *addr;
1259     VsockSocketAddress *vaddr;
1260     struct sockaddr_vm *svm = (struct sockaddr_vm *)sa;
1261 
1262     addr = g_new0(SocketAddress, 1);
1263     addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1264     vaddr = &addr->u.vsock;
1265     vaddr->cid = g_strdup_printf("%u", svm->svm_cid);
1266     vaddr->port = g_strdup_printf("%u", svm->svm_port);
1267 
1268     return addr;
1269 }
1270 #endif /* CONFIG_AF_VSOCK */
1271 
1272 SocketAddress *
1273 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1274                            socklen_t salen,
1275                            Error **errp)
1276 {
1277     switch (sa->ss_family) {
1278     case AF_INET:
1279     case AF_INET6:
1280         return socket_sockaddr_to_address_inet(sa, salen, errp);
1281 
1282 #ifndef WIN32
1283     case AF_UNIX:
1284         return socket_sockaddr_to_address_unix(sa, salen, errp);
1285 #endif /* WIN32 */
1286 
1287 #ifdef CONFIG_AF_VSOCK
1288     case AF_VSOCK:
1289         return socket_sockaddr_to_address_vsock(sa, salen, errp);
1290 #endif
1291 
1292     default:
1293         error_setg(errp, "socket family %d unsupported",
1294                    sa->ss_family);
1295         return NULL;
1296     }
1297     return 0;
1298 }
1299 
1300 
1301 SocketAddress *socket_local_address(int fd, Error **errp)
1302 {
1303     struct sockaddr_storage ss;
1304     socklen_t sslen = sizeof(ss);
1305 
1306     if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1307         error_setg_errno(errp, errno, "%s",
1308                          "Unable to query local socket address");
1309         return NULL;
1310     }
1311 
1312     return socket_sockaddr_to_address(&ss, sslen, errp);
1313 }
1314 
1315 
1316 SocketAddress *socket_remote_address(int fd, Error **errp)
1317 {
1318     struct sockaddr_storage ss;
1319     socklen_t sslen = sizeof(ss);
1320 
1321     if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1322         error_setg_errno(errp, errno, "%s",
1323                          "Unable to query remote socket address");
1324         return NULL;
1325     }
1326 
1327     return socket_sockaddr_to_address(&ss, sslen, errp);
1328 }
1329 
1330 
1331 SocketAddress *socket_address_flatten(SocketAddressLegacy *addr_legacy)
1332 {
1333     SocketAddress *addr;
1334 
1335     if (!addr_legacy) {
1336         return NULL;
1337     }
1338 
1339     addr = g_new(SocketAddress, 1);
1340 
1341     switch (addr_legacy->type) {
1342     case SOCKET_ADDRESS_LEGACY_KIND_INET:
1343         addr->type = SOCKET_ADDRESS_TYPE_INET;
1344         QAPI_CLONE_MEMBERS(InetSocketAddress, &addr->u.inet,
1345                            addr_legacy->u.inet.data);
1346         break;
1347     case SOCKET_ADDRESS_LEGACY_KIND_UNIX:
1348         addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1349         QAPI_CLONE_MEMBERS(UnixSocketAddress, &addr->u.q_unix,
1350                            addr_legacy->u.q_unix.data);
1351         break;
1352     case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:
1353         addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1354         QAPI_CLONE_MEMBERS(VsockSocketAddress, &addr->u.vsock,
1355                            addr_legacy->u.vsock.data);
1356         break;
1357     case SOCKET_ADDRESS_LEGACY_KIND_FD:
1358         addr->type = SOCKET_ADDRESS_TYPE_FD;
1359         QAPI_CLONE_MEMBERS(String, &addr->u.fd, addr_legacy->u.fd.data);
1360         break;
1361     default:
1362         abort();
1363     }
1364 
1365     return addr;
1366 }
1367