1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21#include "qemu/osdep.h"
22#include "qemu-common.h"
23#include "qemu/sockets.h"
24#include "socket-helpers.h"
25
26#ifndef AI_ADDRCONFIG
27# define AI_ADDRCONFIG 0
28#endif
29#ifndef EAI_ADDRFAMILY
30# define EAI_ADDRFAMILY 0
31#endif
32
33int socket_can_bind_connect(const char *hostname)
34{
35 int lfd = -1, cfd = -1, afd = -1;
36 struct addrinfo ai, *res = NULL;
37 struct sockaddr_storage ss;
38 socklen_t sslen = sizeof(ss);
39 int soerr;
40 socklen_t soerrlen = sizeof(soerr);
41 bool check_soerr = false;
42 int rc;
43 int ret = -1;
44
45 memset(&ai, 0, sizeof(ai));
46 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
47 ai.ai_family = AF_UNSPEC;
48 ai.ai_socktype = SOCK_STREAM;
49
50
51 rc = getaddrinfo(hostname, NULL, &ai, &res);
52 if (rc != 0) {
53 if (rc == EAI_ADDRFAMILY ||
54 rc == EAI_FAMILY) {
55 errno = EADDRNOTAVAIL;
56 } else {
57 errno = EINVAL;
58 }
59 goto cleanup;
60 }
61
62 lfd = qemu_socket(res->ai_family, res->ai_socktype, res->ai_protocol);
63 if (lfd < 0) {
64 goto cleanup;
65 }
66
67 cfd = qemu_socket(res->ai_family, res->ai_socktype, res->ai_protocol);
68 if (cfd < 0) {
69 goto cleanup;
70 }
71
72 if (bind(lfd, res->ai_addr, res->ai_addrlen) < 0) {
73 goto cleanup;
74 }
75
76 if (listen(lfd, 1) < 0) {
77 goto cleanup;
78 }
79
80 if (getsockname(lfd, (struct sockaddr *)&ss, &sslen) < 0) {
81 goto cleanup;
82 }
83
84 qemu_set_nonblock(cfd);
85 if (connect(cfd, (struct sockaddr *)&ss, sslen) < 0) {
86 if (errno == EINPROGRESS) {
87 check_soerr = true;
88 } else {
89 goto cleanup;
90 }
91 }
92
93 sslen = sizeof(ss);
94 afd = accept(lfd, (struct sockaddr *)&ss, &sslen);
95 if (afd < 0) {
96 goto cleanup;
97 }
98
99 if (check_soerr) {
100 if (qemu_getsockopt(cfd, SOL_SOCKET, SO_ERROR, &soerr, &soerrlen) < 0) {
101 goto cleanup;
102 }
103 if (soerr) {
104 errno = soerr;
105 goto cleanup;
106 }
107 }
108
109 ret = 0;
110
111 cleanup:
112 if (afd != -1) {
113 close(afd);
114 }
115 if (cfd != -1) {
116 close(cfd);
117 }
118 if (lfd != -1) {
119 close(lfd);
120 }
121 if (res) {
122 freeaddrinfo(res);
123 }
124 return ret;
125}
126
127
128int socket_check_protocol_support(bool *has_ipv4, bool *has_ipv6)
129{
130 *has_ipv4 = *has_ipv6 = false;
131
132 if (socket_can_bind_connect("127.0.0.1") < 0) {
133 if (errno != EADDRNOTAVAIL) {
134 return -1;
135 }
136 } else {
137 *has_ipv4 = true;
138 }
139
140 if (socket_can_bind_connect("::1") < 0) {
141 if (errno != EADDRNOTAVAIL) {
142 return -1;
143 }
144 } else {
145 *has_ipv6 = true;
146 }
147
148 return 0;
149}
150