]> git.proxmox.com Git - mirror_qemu.git/blob - util/qemu-sockets.c
include/qemu/osdep.h: Don't include qapi/error.h
[mirror_qemu.git] / util / qemu-sockets.c
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 #include "monitor/monitor.h"
21 #include "qapi/error.h"
22 #include "qemu/sockets.h"
23 #include "qemu/main-loop.h"
24 #include "qapi/qmp-input-visitor.h"
25 #include "qapi/qmp-output-visitor.h"
26 #include "qapi-visit.h"
27
28 #ifndef AI_ADDRCONFIG
29 # define AI_ADDRCONFIG 0
30 #endif
31 #ifndef AI_V4MAPPED
32 # define AI_V4MAPPED 0
33 #endif
34
35
36 static int inet_getport(struct addrinfo *e)
37 {
38 struct sockaddr_in *i4;
39 struct sockaddr_in6 *i6;
40
41 switch (e->ai_family) {
42 case PF_INET6:
43 i6 = (void*)e->ai_addr;
44 return ntohs(i6->sin6_port);
45 case PF_INET:
46 i4 = (void*)e->ai_addr;
47 return ntohs(i4->sin_port);
48 default:
49 return 0;
50 }
51 }
52
53 static void inet_setport(struct addrinfo *e, int port)
54 {
55 struct sockaddr_in *i4;
56 struct sockaddr_in6 *i6;
57
58 switch (e->ai_family) {
59 case PF_INET6:
60 i6 = (void*)e->ai_addr;
61 i6->sin6_port = htons(port);
62 break;
63 case PF_INET:
64 i4 = (void*)e->ai_addr;
65 i4->sin_port = htons(port);
66 break;
67 }
68 }
69
70 NetworkAddressFamily inet_netfamily(int family)
71 {
72 switch (family) {
73 case PF_INET6: return NETWORK_ADDRESS_FAMILY_IPV6;
74 case PF_INET: return NETWORK_ADDRESS_FAMILY_IPV4;
75 case PF_UNIX: return NETWORK_ADDRESS_FAMILY_UNIX;
76 }
77 return NETWORK_ADDRESS_FAMILY_UNKNOWN;
78 }
79
80 /*
81 * Matrix we're trying to apply
82 *
83 * ipv4 ipv6 family
84 * - - PF_UNSPEC
85 * - f PF_INET
86 * - t PF_INET6
87 * f - PF_INET6
88 * f f <error>
89 * f t PF_INET6
90 * t - PF_INET
91 * t f PF_INET
92 * t t PF_INET6
93 *
94 * NB, this matrix is only about getting the neccessary results
95 * from getaddrinfo(). Some of the cases require further work
96 * after reading results from getaddrinfo in order to fully
97 * apply the logic the end user wants. eg with the last case
98 * ipv4=t + ipv6=t + PF_INET6, getaddrinfo alone can only
99 * guarantee the ipv6=t part of the request - we need more
100 * checks to provide ipv4=t part of the guarantee. This is
101 * outside scope of this method and not currently handled by
102 * callers at all.
103 */
104 static int inet_ai_family_from_address(InetSocketAddress *addr,
105 Error **errp)
106 {
107 if (addr->has_ipv6 && addr->has_ipv4 &&
108 !addr->ipv6 && !addr->ipv4) {
109 error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
110 return PF_UNSPEC;
111 }
112 if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
113 return PF_INET6;
114 }
115 if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
116 return PF_INET;
117 }
118 return PF_UNSPEC;
119 }
120
121 static int inet_listen_saddr(InetSocketAddress *saddr,
122 int port_offset,
123 bool update_addr,
124 Error **errp)
125 {
126 struct addrinfo ai,*res,*e;
127 char port[33];
128 char uaddr[INET6_ADDRSTRLEN+1];
129 char uport[33];
130 int slisten, rc, port_min, port_max, p;
131 Error *err = NULL;
132
133 memset(&ai,0, sizeof(ai));
134 ai.ai_flags = AI_PASSIVE;
135 ai.ai_family = inet_ai_family_from_address(saddr, &err);
136 ai.ai_socktype = SOCK_STREAM;
137
138 if (err) {
139 error_propagate(errp, err);
140 return -1;
141 }
142
143 if (saddr->host == NULL) {
144 error_setg(errp, "host not specified");
145 return -1;
146 }
147 if (saddr->port != NULL) {
148 pstrcpy(port, sizeof(port), saddr->port);
149 } else {
150 port[0] = '\0';
151 }
152
153 /* lookup */
154 if (port_offset) {
155 unsigned long long baseport;
156 if (strlen(port) == 0) {
157 error_setg(errp, "port not specified");
158 return -1;
159 }
160 if (parse_uint_full(port, &baseport, 10) < 0) {
161 error_setg(errp, "can't convert to a number: %s", port);
162 return -1;
163 }
164 if (baseport > 65535 ||
165 baseport + port_offset > 65535) {
166 error_setg(errp, "port %s out of range", port);
167 return -1;
168 }
169 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
170 }
171 rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
172 strlen(port) ? port : NULL, &ai, &res);
173 if (rc != 0) {
174 error_setg(errp, "address resolution failed for %s:%s: %s",
175 saddr->host, port, gai_strerror(rc));
176 return -1;
177 }
178
179 /* create socket + bind */
180 for (e = res; e != NULL; e = e->ai_next) {
181 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
182 uaddr,INET6_ADDRSTRLEN,uport,32,
183 NI_NUMERICHOST | NI_NUMERICSERV);
184 slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
185 if (slisten < 0) {
186 if (!e->ai_next) {
187 error_setg_errno(errp, errno, "Failed to create socket");
188 }
189 continue;
190 }
191
192 socket_set_fast_reuse(slisten);
193 #ifdef IPV6_V6ONLY
194 if (e->ai_family == PF_INET6) {
195 /* listen on both ipv4 and ipv6 */
196 const int off = 0;
197 qemu_setsockopt(slisten, IPPROTO_IPV6, IPV6_V6ONLY, &off,
198 sizeof(off));
199 }
200 #endif
201
202 port_min = inet_getport(e);
203 port_max = saddr->has_to ? saddr->to + port_offset : port_min;
204 for (p = port_min; p <= port_max; p++) {
205 inet_setport(e, p);
206 if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {
207 goto listen;
208 }
209 if (p == port_max) {
210 if (!e->ai_next) {
211 error_setg_errno(errp, errno, "Failed to bind socket");
212 }
213 }
214 }
215 closesocket(slisten);
216 }
217 freeaddrinfo(res);
218 return -1;
219
220 listen:
221 if (listen(slisten,1) != 0) {
222 error_setg_errno(errp, errno, "Failed to listen on socket");
223 closesocket(slisten);
224 freeaddrinfo(res);
225 return -1;
226 }
227 if (update_addr) {
228 g_free(saddr->host);
229 saddr->host = g_strdup(uaddr);
230 g_free(saddr->port);
231 saddr->port = g_strdup_printf("%d",
232 inet_getport(e) - port_offset);
233 saddr->has_ipv6 = saddr->ipv6 = e->ai_family == PF_INET6;
234 saddr->has_ipv4 = saddr->ipv4 = e->ai_family != PF_INET6;
235 }
236 freeaddrinfo(res);
237 return slisten;
238 }
239
240 #ifdef _WIN32
241 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
242 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
243 #else
244 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
245 ((rc) == -EINPROGRESS)
246 #endif
247
248 /* Struct to store connect state for non blocking connect */
249 typedef struct ConnectState {
250 int fd;
251 struct addrinfo *addr_list;
252 struct addrinfo *current_addr;
253 NonBlockingConnectHandler *callback;
254 void *opaque;
255 } ConnectState;
256
257 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
258 ConnectState *connect_state, Error **errp);
259
260 static void wait_for_connect(void *opaque)
261 {
262 ConnectState *s = opaque;
263 int val = 0, rc = 0;
264 socklen_t valsize = sizeof(val);
265 bool in_progress;
266 Error *err = NULL;
267
268 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
269
270 do {
271 rc = qemu_getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &val, &valsize);
272 } while (rc == -1 && errno == EINTR);
273
274 /* update rc to contain error */
275 if (!rc && val) {
276 rc = -1;
277 errno = val;
278 }
279
280 /* connect error */
281 if (rc < 0) {
282 error_setg_errno(&err, errno, "Error connecting to socket");
283 closesocket(s->fd);
284 s->fd = rc;
285 }
286
287 /* try to connect to the next address on the list */
288 if (s->current_addr) {
289 while (s->current_addr->ai_next != NULL && s->fd < 0) {
290 s->current_addr = s->current_addr->ai_next;
291 s->fd = inet_connect_addr(s->current_addr, &in_progress, s, NULL);
292 if (s->fd < 0) {
293 error_free(err);
294 err = NULL;
295 error_setg_errno(&err, errno, "Unable to start socket connect");
296 }
297 /* connect in progress */
298 if (in_progress) {
299 goto out;
300 }
301 }
302
303 freeaddrinfo(s->addr_list);
304 }
305
306 if (s->callback) {
307 s->callback(s->fd, err, s->opaque);
308 }
309 g_free(s);
310 out:
311 error_free(err);
312 }
313
314 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
315 ConnectState *connect_state, Error **errp)
316 {
317 int sock, rc;
318
319 *in_progress = false;
320
321 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
322 if (sock < 0) {
323 error_setg_errno(errp, errno, "Failed to create socket");
324 return -1;
325 }
326 socket_set_fast_reuse(sock);
327 if (connect_state != NULL) {
328 qemu_set_nonblock(sock);
329 }
330 /* connect to peer */
331 do {
332 rc = 0;
333 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
334 rc = -errno;
335 }
336 } while (rc == -EINTR);
337
338 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
339 connect_state->fd = sock;
340 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
341 *in_progress = true;
342 } else if (rc < 0) {
343 error_setg_errno(errp, errno, "Failed to connect socket");
344 closesocket(sock);
345 return -1;
346 }
347 return sock;
348 }
349
350 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
351 Error **errp)
352 {
353 struct addrinfo ai, *res;
354 int rc;
355 Error *err = NULL;
356
357 memset(&ai, 0, sizeof(ai));
358
359 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
360 ai.ai_family = inet_ai_family_from_address(saddr, &err);
361 ai.ai_socktype = SOCK_STREAM;
362
363 if (err) {
364 error_propagate(errp, err);
365 return NULL;
366 }
367
368 if (saddr->host == NULL || saddr->port == NULL) {
369 error_setg(errp, "host and/or port not specified");
370 return NULL;
371 }
372
373 /* lookup */
374 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
375 if (rc != 0) {
376 error_setg(errp, "address resolution failed for %s:%s: %s",
377 saddr->host, saddr->port, gai_strerror(rc));
378 return NULL;
379 }
380 return res;
381 }
382
383 /**
384 * Create a socket and connect it to an address.
385 *
386 * @saddr: Inet socket address specification
387 * @errp: set on error
388 * @callback: callback function for non-blocking connect
389 * @opaque: opaque for callback function
390 *
391 * Returns: -1 on error, file descriptor on success.
392 *
393 * If @callback is non-null, the connect is non-blocking. If this
394 * function succeeds, callback will be called when the connection
395 * completes, with the file descriptor on success, or -1 on error.
396 */
397 static int inet_connect_saddr(InetSocketAddress *saddr, Error **errp,
398 NonBlockingConnectHandler *callback, void *opaque)
399 {
400 Error *local_err = NULL;
401 struct addrinfo *res, *e;
402 int sock = -1;
403 bool in_progress;
404 ConnectState *connect_state = NULL;
405
406 res = inet_parse_connect_saddr(saddr, errp);
407 if (!res) {
408 return -1;
409 }
410
411 if (callback != NULL) {
412 connect_state = g_malloc0(sizeof(*connect_state));
413 connect_state->addr_list = res;
414 connect_state->callback = callback;
415 connect_state->opaque = opaque;
416 }
417
418 for (e = res; e != NULL; e = e->ai_next) {
419 error_free(local_err);
420 local_err = NULL;
421 if (connect_state != NULL) {
422 connect_state->current_addr = e;
423 }
424 sock = inet_connect_addr(e, &in_progress, connect_state, &local_err);
425 if (sock >= 0) {
426 break;
427 }
428 }
429
430 if (sock < 0) {
431 error_propagate(errp, local_err);
432 } else if (in_progress) {
433 /* wait_for_connect() will do the rest */
434 return sock;
435 } else {
436 if (callback) {
437 callback(sock, NULL, opaque);
438 }
439 }
440 g_free(connect_state);
441 freeaddrinfo(res);
442 return sock;
443 }
444
445 static int inet_dgram_saddr(InetSocketAddress *sraddr,
446 InetSocketAddress *sladdr,
447 Error **errp)
448 {
449 struct addrinfo ai, *peer = NULL, *local = NULL;
450 const char *addr;
451 const char *port;
452 int sock = -1, rc;
453 Error *err = NULL;
454
455 /* lookup peer addr */
456 memset(&ai,0, sizeof(ai));
457 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
458 ai.ai_family = inet_ai_family_from_address(sraddr, &err);
459 ai.ai_socktype = SOCK_DGRAM;
460
461 if (err) {
462 error_propagate(errp, err);
463 goto err;
464 }
465
466 addr = sraddr->host;
467 port = sraddr->port;
468 if (addr == NULL || strlen(addr) == 0) {
469 addr = "localhost";
470 }
471 if (port == NULL || strlen(port) == 0) {
472 error_setg(errp, "remote port not specified");
473 goto err;
474 }
475
476 if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {
477 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
478 gai_strerror(rc));
479 goto err;
480 }
481
482 /* lookup local addr */
483 memset(&ai,0, sizeof(ai));
484 ai.ai_flags = AI_PASSIVE;
485 ai.ai_family = peer->ai_family;
486 ai.ai_socktype = SOCK_DGRAM;
487
488 if (sladdr) {
489 addr = sladdr->host;
490 port = sladdr->port;
491 if (addr == NULL || strlen(addr) == 0) {
492 addr = NULL;
493 }
494 if (!port || strlen(port) == 0) {
495 port = "0";
496 }
497 } else {
498 addr = NULL;
499 port = "0";
500 }
501
502 if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {
503 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
504 gai_strerror(rc));
505 goto err;
506 }
507
508 /* create socket */
509 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
510 if (sock < 0) {
511 error_setg_errno(errp, errno, "Failed to create socket");
512 goto err;
513 }
514 socket_set_fast_reuse(sock);
515
516 /* bind socket */
517 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
518 error_setg_errno(errp, errno, "Failed to bind socket");
519 goto err;
520 }
521
522 /* connect to peer */
523 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
524 error_setg_errno(errp, errno, "Failed to connect socket");
525 goto err;
526 }
527
528 freeaddrinfo(local);
529 freeaddrinfo(peer);
530 return sock;
531
532 err:
533 if (-1 != sock)
534 closesocket(sock);
535 if (local)
536 freeaddrinfo(local);
537 if (peer)
538 freeaddrinfo(peer);
539 return -1;
540 }
541
542 /* compatibility wrapper */
543 InetSocketAddress *inet_parse(const char *str, Error **errp)
544 {
545 InetSocketAddress *addr;
546 const char *optstr, *h;
547 char host[65];
548 char port[33];
549 int to;
550 int pos;
551
552 addr = g_new0(InetSocketAddress, 1);
553
554 /* parse address */
555 if (str[0] == ':') {
556 /* no host given */
557 host[0] = '\0';
558 if (1 != sscanf(str, ":%32[^,]%n", port, &pos)) {
559 error_setg(errp, "error parsing port in address '%s'", str);
560 goto fail;
561 }
562 } else if (str[0] == '[') {
563 /* IPv6 addr */
564 if (2 != sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos)) {
565 error_setg(errp, "error parsing IPv6 address '%s'", str);
566 goto fail;
567 }
568 addr->ipv6 = addr->has_ipv6 = true;
569 } else {
570 /* hostname or IPv4 addr */
571 if (2 != sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos)) {
572 error_setg(errp, "error parsing address '%s'", str);
573 goto fail;
574 }
575 if (host[strspn(host, "0123456789.")] == '\0') {
576 addr->ipv4 = addr->has_ipv4 = true;
577 }
578 }
579
580 addr->host = g_strdup(host);
581 addr->port = g_strdup(port);
582
583 /* parse options */
584 optstr = str + pos;
585 h = strstr(optstr, ",to=");
586 if (h) {
587 h += 4;
588 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
589 (h[pos] != '\0' && h[pos] != ',')) {
590 error_setg(errp, "error parsing to= argument");
591 goto fail;
592 }
593 addr->has_to = true;
594 addr->to = to;
595 }
596 if (strstr(optstr, ",ipv4")) {
597 addr->ipv4 = addr->has_ipv4 = true;
598 }
599 if (strstr(optstr, ",ipv6")) {
600 addr->ipv6 = addr->has_ipv6 = true;
601 }
602 return addr;
603
604 fail:
605 qapi_free_InetSocketAddress(addr);
606 return NULL;
607 }
608
609 int inet_listen(const char *str, char *ostr, int olen,
610 int socktype, int port_offset, Error **errp)
611 {
612 char *optstr;
613 int sock = -1;
614 InetSocketAddress *addr;
615
616 addr = inet_parse(str, errp);
617 if (addr != NULL) {
618 sock = inet_listen_saddr(addr, port_offset, true, errp);
619 if (sock != -1 && ostr) {
620 optstr = strchr(str, ',');
621 if (addr->ipv6) {
622 snprintf(ostr, olen, "[%s]:%s%s",
623 addr->host,
624 addr->port,
625 optstr ? optstr : "");
626 } else {
627 snprintf(ostr, olen, "%s:%s%s",
628 addr->host,
629 addr->port,
630 optstr ? optstr : "");
631 }
632 }
633 qapi_free_InetSocketAddress(addr);
634 }
635 return sock;
636 }
637
638 /**
639 * Create a blocking socket and connect it to an address.
640 *
641 * @str: address string
642 * @errp: set in case of an error
643 *
644 * Returns -1 in case of error, file descriptor on success
645 **/
646 int inet_connect(const char *str, Error **errp)
647 {
648 int sock = -1;
649 InetSocketAddress *addr;
650
651 addr = inet_parse(str, errp);
652 if (addr != NULL) {
653 sock = inet_connect_saddr(addr, errp, NULL, NULL);
654 qapi_free_InetSocketAddress(addr);
655 }
656 return sock;
657 }
658
659 /**
660 * Create a non-blocking socket and connect it to an address.
661 * Calls the callback function with fd in case of success or -1 in case of
662 * error.
663 *
664 * @str: address string
665 * @callback: callback function that is called when connect completes,
666 * cannot be NULL.
667 * @opaque: opaque for callback function
668 * @errp: set in case of an error
669 *
670 * Returns: -1 on immediate error, file descriptor on success.
671 **/
672 int inet_nonblocking_connect(const char *str,
673 NonBlockingConnectHandler *callback,
674 void *opaque, Error **errp)
675 {
676 int sock = -1;
677 InetSocketAddress *addr;
678
679 g_assert(callback != NULL);
680
681 addr = inet_parse(str, errp);
682 if (addr != NULL) {
683 sock = inet_connect_saddr(addr, errp, callback, opaque);
684 qapi_free_InetSocketAddress(addr);
685 }
686 return sock;
687 }
688
689 #ifndef _WIN32
690
691 static int unix_listen_saddr(UnixSocketAddress *saddr,
692 bool update_addr,
693 Error **errp)
694 {
695 struct sockaddr_un un;
696 int sock, fd;
697
698 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
699 if (sock < 0) {
700 error_setg_errno(errp, errno, "Failed to create Unix socket");
701 return -1;
702 }
703
704 memset(&un, 0, sizeof(un));
705 un.sun_family = AF_UNIX;
706 if (saddr->path && strlen(saddr->path)) {
707 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
708 } else {
709 const char *tmpdir = getenv("TMPDIR");
710 tmpdir = tmpdir ? tmpdir : "/tmp";
711 if (snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
712 tmpdir) >= sizeof(un.sun_path)) {
713 error_setg_errno(errp, errno,
714 "TMPDIR environment variable (%s) too large", tmpdir);
715 goto err;
716 }
717
718 /*
719 * This dummy fd usage silences the mktemp() unsecure warning.
720 * Using mkstemp() doesn't make things more secure here
721 * though. bind() complains about existing files, so we have
722 * to unlink first and thus re-open the race window. The
723 * worst case possible is bind() failing, i.e. a DoS attack.
724 */
725 fd = mkstemp(un.sun_path);
726 if (fd < 0) {
727 error_setg_errno(errp, errno,
728 "Failed to make a temporary socket name in %s", tmpdir);
729 goto err;
730 }
731 close(fd);
732 if (update_addr) {
733 g_free(saddr->path);
734 saddr->path = g_strdup(un.sun_path);
735 }
736 }
737
738 if (unlink(un.sun_path) < 0 && errno != ENOENT) {
739 error_setg_errno(errp, errno,
740 "Failed to unlink socket %s", un.sun_path);
741 goto err;
742 }
743 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
744 error_setg_errno(errp, errno, "Failed to bind socket to %s", un.sun_path);
745 goto err;
746 }
747 if (listen(sock, 1) < 0) {
748 error_setg_errno(errp, errno, "Failed to listen on socket");
749 goto err;
750 }
751
752 return sock;
753
754 err:
755 closesocket(sock);
756 return -1;
757 }
758
759 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp,
760 NonBlockingConnectHandler *callback, void *opaque)
761 {
762 struct sockaddr_un un;
763 ConnectState *connect_state = NULL;
764 int sock, rc;
765
766 if (saddr->path == NULL) {
767 error_setg(errp, "unix connect: no path specified");
768 return -1;
769 }
770
771 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
772 if (sock < 0) {
773 error_setg_errno(errp, errno, "Failed to create socket");
774 return -1;
775 }
776 if (callback != NULL) {
777 connect_state = g_malloc0(sizeof(*connect_state));
778 connect_state->callback = callback;
779 connect_state->opaque = opaque;
780 qemu_set_nonblock(sock);
781 }
782
783 memset(&un, 0, sizeof(un));
784 un.sun_family = AF_UNIX;
785 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
786
787 /* connect to peer */
788 do {
789 rc = 0;
790 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
791 rc = -errno;
792 }
793 } while (rc == -EINTR);
794
795 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
796 connect_state->fd = sock;
797 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
798 return sock;
799 } else if (rc >= 0) {
800 /* non blocking socket immediate success, call callback */
801 if (callback != NULL) {
802 callback(sock, NULL, opaque);
803 }
804 }
805
806 if (rc < 0) {
807 error_setg_errno(errp, -rc, "Failed to connect socket");
808 close(sock);
809 sock = -1;
810 }
811
812 g_free(connect_state);
813 return sock;
814 }
815
816 #else
817
818 static int unix_listen_saddr(UnixSocketAddress *saddr,
819 bool update_addr,
820 Error **errp)
821 {
822 error_setg(errp, "unix sockets are not available on windows");
823 errno = ENOTSUP;
824 return -1;
825 }
826
827 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp,
828 NonBlockingConnectHandler *callback, void *opaque)
829 {
830 error_setg(errp, "unix sockets are not available on windows");
831 errno = ENOTSUP;
832 return -1;
833 }
834 #endif
835
836 /* compatibility wrapper */
837 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
838 {
839 char *path, *optstr;
840 int sock, len;
841 UnixSocketAddress *saddr;
842
843 saddr = g_new0(UnixSocketAddress, 1);
844
845 optstr = strchr(str, ',');
846 if (optstr) {
847 len = optstr - str;
848 if (len) {
849 path = g_malloc(len+1);
850 snprintf(path, len+1, "%.*s", len, str);
851 saddr->path = path;
852 }
853 } else {
854 saddr->path = g_strdup(str);
855 }
856
857 sock = unix_listen_saddr(saddr, true, errp);
858
859 if (sock != -1 && ostr)
860 snprintf(ostr, olen, "%s%s", saddr->path, optstr ? optstr : "");
861 qapi_free_UnixSocketAddress(saddr);
862 return sock;
863 }
864
865 int unix_connect(const char *path, Error **errp)
866 {
867 UnixSocketAddress *saddr;
868 int sock;
869
870 saddr = g_new0(UnixSocketAddress, 1);
871 saddr->path = g_strdup(path);
872 sock = unix_connect_saddr(saddr, errp, NULL, NULL);
873 qapi_free_UnixSocketAddress(saddr);
874 return sock;
875 }
876
877
878 int unix_nonblocking_connect(const char *path,
879 NonBlockingConnectHandler *callback,
880 void *opaque, Error **errp)
881 {
882 UnixSocketAddress *saddr;
883 int sock = -1;
884
885 g_assert(callback != NULL);
886
887 saddr = g_new0(UnixSocketAddress, 1);
888 saddr->path = g_strdup(path);
889 sock = unix_connect_saddr(saddr, errp, callback, opaque);
890 qapi_free_UnixSocketAddress(saddr);
891 return sock;
892 }
893
894 SocketAddress *socket_parse(const char *str, Error **errp)
895 {
896 SocketAddress *addr;
897
898 addr = g_new0(SocketAddress, 1);
899 if (strstart(str, "unix:", NULL)) {
900 if (str[5] == '\0') {
901 error_setg(errp, "invalid Unix socket address");
902 goto fail;
903 } else {
904 addr->type = SOCKET_ADDRESS_KIND_UNIX;
905 addr->u.q_unix.data = g_new(UnixSocketAddress, 1);
906 addr->u.q_unix.data->path = g_strdup(str + 5);
907 }
908 } else if (strstart(str, "fd:", NULL)) {
909 if (str[3] == '\0') {
910 error_setg(errp, "invalid file descriptor address");
911 goto fail;
912 } else {
913 addr->type = SOCKET_ADDRESS_KIND_FD;
914 addr->u.fd.data = g_new(String, 1);
915 addr->u.fd.data->str = g_strdup(str + 3);
916 }
917 } else {
918 addr->type = SOCKET_ADDRESS_KIND_INET;
919 addr->u.inet.data = inet_parse(str, errp);
920 if (addr->u.inet.data == NULL) {
921 goto fail;
922 }
923 }
924 return addr;
925
926 fail:
927 qapi_free_SocketAddress(addr);
928 return NULL;
929 }
930
931 int socket_connect(SocketAddress *addr, Error **errp,
932 NonBlockingConnectHandler *callback, void *opaque)
933 {
934 int fd;
935
936 switch (addr->type) {
937 case SOCKET_ADDRESS_KIND_INET:
938 fd = inet_connect_saddr(addr->u.inet.data, errp, callback, opaque);
939 break;
940
941 case SOCKET_ADDRESS_KIND_UNIX:
942 fd = unix_connect_saddr(addr->u.q_unix.data, errp, callback, opaque);
943 break;
944
945 case SOCKET_ADDRESS_KIND_FD:
946 fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
947 if (fd >= 0 && callback) {
948 qemu_set_nonblock(fd);
949 callback(fd, NULL, opaque);
950 }
951 break;
952
953 default:
954 abort();
955 }
956 return fd;
957 }
958
959 int socket_listen(SocketAddress *addr, Error **errp)
960 {
961 int fd;
962
963 switch (addr->type) {
964 case SOCKET_ADDRESS_KIND_INET:
965 fd = inet_listen_saddr(addr->u.inet.data, 0, false, errp);
966 break;
967
968 case SOCKET_ADDRESS_KIND_UNIX:
969 fd = unix_listen_saddr(addr->u.q_unix.data, false, errp);
970 break;
971
972 case SOCKET_ADDRESS_KIND_FD:
973 fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
974 break;
975
976 default:
977 abort();
978 }
979 return fd;
980 }
981
982 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
983 {
984 int fd;
985
986 switch (remote->type) {
987 case SOCKET_ADDRESS_KIND_INET:
988 fd = inet_dgram_saddr(remote->u.inet.data,
989 local ? local->u.inet.data : NULL, errp);
990 break;
991
992 default:
993 error_setg(errp, "socket type unsupported for datagram");
994 fd = -1;
995 }
996 return fd;
997 }
998
999
1000 static SocketAddress *
1001 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1002 socklen_t salen,
1003 Error **errp)
1004 {
1005 char host[NI_MAXHOST];
1006 char serv[NI_MAXSERV];
1007 SocketAddress *addr;
1008 InetSocketAddress *inet;
1009 int ret;
1010
1011 ret = getnameinfo((struct sockaddr *)sa, salen,
1012 host, sizeof(host),
1013 serv, sizeof(serv),
1014 NI_NUMERICHOST | NI_NUMERICSERV);
1015 if (ret != 0) {
1016 error_setg(errp, "Cannot format numeric socket address: %s",
1017 gai_strerror(ret));
1018 return NULL;
1019 }
1020
1021 addr = g_new0(SocketAddress, 1);
1022 addr->type = SOCKET_ADDRESS_KIND_INET;
1023 inet = addr->u.inet.data = g_new0(InetSocketAddress, 1);
1024 inet->host = g_strdup(host);
1025 inet->port = g_strdup(serv);
1026 if (sa->ss_family == AF_INET) {
1027 inet->has_ipv4 = inet->ipv4 = true;
1028 } else {
1029 inet->has_ipv6 = inet->ipv6 = true;
1030 }
1031
1032 return addr;
1033 }
1034
1035
1036 #ifndef WIN32
1037 static SocketAddress *
1038 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1039 socklen_t salen,
1040 Error **errp)
1041 {
1042 SocketAddress *addr;
1043 struct sockaddr_un *su = (struct sockaddr_un *)sa;
1044
1045 addr = g_new0(SocketAddress, 1);
1046 addr->type = SOCKET_ADDRESS_KIND_UNIX;
1047 addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
1048 if (su->sun_path[0]) {
1049 addr->u.q_unix.data->path = g_strndup(su->sun_path,
1050 sizeof(su->sun_path));
1051 }
1052
1053 return addr;
1054 }
1055 #endif /* WIN32 */
1056
1057 SocketAddress *
1058 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1059 socklen_t salen,
1060 Error **errp)
1061 {
1062 switch (sa->ss_family) {
1063 case AF_INET:
1064 case AF_INET6:
1065 return socket_sockaddr_to_address_inet(sa, salen, errp);
1066
1067 #ifndef WIN32
1068 case AF_UNIX:
1069 return socket_sockaddr_to_address_unix(sa, salen, errp);
1070 #endif /* WIN32 */
1071
1072 default:
1073 error_setg(errp, "socket family %d unsupported",
1074 sa->ss_family);
1075 return NULL;
1076 }
1077 return 0;
1078 }
1079
1080
1081 SocketAddress *socket_local_address(int fd, Error **errp)
1082 {
1083 struct sockaddr_storage ss;
1084 socklen_t sslen = sizeof(ss);
1085
1086 if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1087 error_setg_errno(errp, errno, "%s",
1088 "Unable to query local socket address");
1089 return NULL;
1090 }
1091
1092 return socket_sockaddr_to_address(&ss, sslen, errp);
1093 }
1094
1095
1096 SocketAddress *socket_remote_address(int fd, Error **errp)
1097 {
1098 struct sockaddr_storage ss;
1099 socklen_t sslen = sizeof(ss);
1100
1101 if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1102 error_setg_errno(errp, errno, "%s",
1103 "Unable to query remote socket address");
1104 return NULL;
1105 }
1106
1107 return socket_sockaddr_to_address(&ss, sslen, errp);
1108 }
1109
1110
1111 void qapi_copy_SocketAddress(SocketAddress **p_dest,
1112 SocketAddress *src)
1113 {
1114 QmpOutputVisitor *qov;
1115 QmpInputVisitor *qiv;
1116 Visitor *ov, *iv;
1117 QObject *obj;
1118
1119 *p_dest = NULL;
1120
1121 qov = qmp_output_visitor_new();
1122 ov = qmp_output_get_visitor(qov);
1123 visit_type_SocketAddress(ov, NULL, &src, &error_abort);
1124 obj = qmp_output_get_qobject(qov);
1125 qmp_output_visitor_cleanup(qov);
1126 if (!obj) {
1127 return;
1128 }
1129
1130 qiv = qmp_input_visitor_new(obj);
1131 iv = qmp_input_get_visitor(qiv);
1132 visit_type_SocketAddress(iv, NULL, p_dest, &error_abort);
1133 qmp_input_visitor_cleanup(qiv);
1134 qobject_decref(obj);
1135 }