Drop AI_ADDRCONFIG when resolving TCP addresses
[free-sw/xcb/libxcb] / src / xcb_util.c
1 /* Copyright (C) 2001-2004 Bart Massey and Jamey Sharp.
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a
4  * copy of this software and associated documentation files (the "Software"),
5  * to deal in the Software without restriction, including without limitation
6  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
7  * and/or sell copies of the Software, and to permit persons to whom the
8  * Software is furnished to do so, subject to the following conditions:
9  * 
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  * 
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
17  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19  * 
20  * Except as contained in this notice, the names of the authors or their
21  * institutions shall not be used in advertising or otherwise to promote the
22  * sale, use or other dealings in this Software without prior written
23  * authorization from the authors.
24  */
25
26 /* Utility functions implementable using only public APIs. */
27
28 #include <assert.h>
29 #include <sys/types.h>
30 #include <limits.h>
31 #include <errno.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <stddef.h>
35 #include <unistd.h>
36 #include <string.h>
37
38 #ifdef _WIN32
39 #include "xcb_windefs.h"
40 #else
41 #include <sys/socket.h>
42 #include <sys/un.h>
43 #include <netinet/in.h>
44 #include <netinet/tcp.h>
45 #include <fcntl.h>
46 #include <netdb.h>
47 #endif /* _WIN32 */
48
49 #include "xcb.h"
50 #include "xcbext.h"
51 #include "xcbint.h"
52
53 /* must be after "xcbint.h" to get autoconf #defines */
54 #if defined(HAVE_TSOL_LABEL_H) && defined(HAVE_IS_SYSTEM_LABELED)
55 # include <tsol/label.h>
56 # include <sys/stat.h>
57 #endif
58
59 int xcb_popcount(uint32_t mask)
60 {
61     uint32_t y;
62     y = (mask >> 1) & 033333333333;
63     y = mask - y - ((y >> 1) & 033333333333);
64     return ((y + (y >> 3)) & 030707070707) % 077;
65 }
66
67 int xcb_sumof(uint8_t *list, int len)
68 {
69   int i, s = 0;
70   for(i=0; i<len; i++) {
71     s += *list;
72     list++;
73   }
74   return s;
75 }
76
77 static int _xcb_parse_display(const char *name, char **host, char **protocol,
78                       int *displayp, int *screenp)
79 {
80     int len, display, screen;
81     char *slash, *colon, *dot, *end;
82
83     if(!name || !*name)
84         name = getenv("DISPLAY");
85     if(!name)
86         return 0;
87
88 #ifdef HAVE_LAUNCHD
89     if(strncmp(name, "/tmp/launch", 11) == 0)
90         slash = NULL;
91     else
92 #endif
93     slash = strrchr(name, '/');
94
95     if (slash) {
96         len = slash - name;
97         if (protocol) {
98             *protocol = malloc(len + 1);
99             if(!*protocol)
100                 return 0;
101             memcpy(*protocol, name, len);
102             (*protocol)[len] = '\0';
103         }
104         name = slash + 1;
105     } else
106         if (protocol)
107             *protocol = NULL;
108
109     colon = strrchr(name, ':');
110     if(!colon)
111         goto error_out;
112     len = colon - name;
113     ++colon;
114     display = strtoul(colon, &dot, 10);
115     if(dot == colon)
116         goto error_out;
117     if(*dot == '\0')
118         screen = 0;
119     else
120     {
121         if(*dot != '.')
122             goto error_out;
123         ++dot;
124         screen = strtoul(dot, &end, 10);
125         if(end == dot || *end != '\0')
126             goto error_out;
127     }
128     /* At this point, the display string is fully parsed and valid, but
129      * the caller's memory is untouched. */
130
131     *host = malloc(len + 1);
132     if(!*host)
133         goto error_out;
134     memcpy(*host, name, len);
135     (*host)[len] = '\0';
136     *displayp = display;
137     if(screenp)
138         *screenp = screen;
139     return 1;
140
141 error_out:
142     if (protocol) {
143         free(*protocol);
144         *protocol = NULL;
145     }
146
147     return 0;
148 }
149
150 int xcb_parse_display(const char *name, char **host, int *displayp,
151                              int *screenp)
152 {
153     return _xcb_parse_display(name, host, NULL, displayp, screenp);
154 }
155
156 static int _xcb_open_tcp(const char *host, char *protocol, const unsigned short port);
157 #ifndef _WIN32
158 static int _xcb_open_unix(char *protocol, const char *file);
159 #endif /* !WIN32 */
160 #ifdef HAVE_ABSTRACT_SOCKETS
161 static int _xcb_open_abstract(char *protocol, const char *file, size_t filelen);
162 #endif
163
164 static int _xcb_open(const char *host, char *protocol, const int display)
165 {
166     int fd;
167     static const char unix_base[] = "/tmp/.X11-unix/X";
168     const char *base = unix_base;
169     size_t filelen;
170     char *file = NULL;
171     int actual_filelen;
172
173 #ifdef HAVE_LAUNCHD
174     if(strncmp(host, "/tmp/launch", 11) == 0) {
175         base = host;
176         host = "";
177         protocol = NULL;
178     }
179 #endif
180
181     /* If protocol or host is "unix", fall through to Unix socket code below */
182     if ((!protocol || (strcmp("unix",protocol) != 0)) &&
183         (*host != '\0') && (strcmp("unix",host) != 0))
184     {
185         /* display specifies TCP */
186         unsigned short port = X_TCP_PORT + display;
187         return _xcb_open_tcp(host, protocol, port);
188     }
189
190 #ifndef _WIN32
191 #if defined(HAVE_TSOL_LABEL_H) && defined(HAVE_IS_SYSTEM_LABELED)
192     /* Check special path for Unix sockets under Solaris Trusted Extensions */
193     if (is_system_labeled())
194     {
195         struct stat sbuf;
196         const char *tsol_base = "/var/tsol/doors/.X11-unix/X";
197         char tsol_socket[PATH_MAX];
198
199         snprintf(tsol_socket, sizeof(tsol_socket), "%s%d", tsol_base, display);
200
201         if (stat(tsol_socket, &sbuf) == 0)
202             base = tsol_base;
203     }
204 #endif
205
206     filelen = strlen(base) + 1 + sizeof(display) * 3 + 1;
207     file = malloc(filelen);
208     if(file == NULL)
209         return -1;
210
211     /* display specifies Unix socket */
212 #ifdef HAVE_LAUNCHD
213     if(strncmp(base, "/tmp/launch", 11) == 0)
214         actual_filelen = snprintf(file, filelen, "%s:%d", base, display);
215     else
216 #endif
217         actual_filelen = snprintf(file, filelen, "%s%d", base, display);
218     if(actual_filelen < 0)
219     {
220         free(file);
221         return -1;
222     }
223     /* snprintf may truncate the file */
224     filelen = MIN(actual_filelen, filelen - 1);
225 #ifdef HAVE_ABSTRACT_SOCKETS
226     fd = _xcb_open_abstract(protocol, file, filelen);
227     if (fd >= 0 || (errno != ENOENT && errno != ECONNREFUSED))
228     {
229         free(file);
230         return fd;
231     }
232
233 #endif
234     fd = _xcb_open_unix(protocol, file);
235     free(file);
236
237     return fd;
238 #endif /* !_WIN32 */
239     return -1; /* if control reaches here then something has gone wrong */
240 }
241
242 static int _xcb_socket(int family, int type, int proto)
243 {
244     int fd;
245
246 #ifdef SOCK_CLOEXEC
247     fd = socket(family, type | SOCK_CLOEXEC, proto);
248     if (fd == -1 && errno == EINVAL)
249 #endif
250     {
251         fd = socket(family, type, proto);
252 #ifndef _WIN32
253         if (fd >= 0)
254             fcntl(fd, F_SETFD, FD_CLOEXEC);
255 #endif
256     }
257     return fd;
258 }
259
260
261 static int _xcb_open_tcp(const char *host, char *protocol, const unsigned short port)
262 {
263     int fd = -1;
264     struct addrinfo hints;
265     char service[6]; /* "65535" with the trailing '\0' */
266     struct addrinfo *results, *addr;
267     char *bracket;
268
269     if (protocol && strcmp("tcp",protocol) && strcmp("inet",protocol)
270 #ifdef AF_INET6
271                  && strcmp("inet6",protocol)
272 #endif
273         )
274         return -1;
275         
276     if (*host == '\0')
277         host = "localhost";
278
279     memset(&hints, 0, sizeof(hints));
280 #ifdef AI_NUMERICSERV
281     hints.ai_flags |= AI_NUMERICSERV;
282 #endif
283     hints.ai_family = AF_UNSPEC;
284     hints.ai_socktype = SOCK_STREAM;
285
286 #ifdef AF_INET6
287     /* Allow IPv6 addresses enclosed in brackets. */
288     if(host[0] == '[' && (bracket = strrchr(host, ']')) && bracket[1] == '\0')
289     {
290         *bracket = '\0';
291         ++host;
292         hints.ai_flags |= AI_NUMERICHOST;
293         hints.ai_family = AF_INET6;
294     }
295 #endif
296
297     snprintf(service, sizeof(service), "%hu", port);
298     if(getaddrinfo(host, service, &hints, &results))
299         /* FIXME: use gai_strerror, and fill in error connection */
300         return -1;
301
302     for(addr = results; addr; addr = addr->ai_next)
303     {
304         fd = _xcb_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
305         if(fd >= 0) {
306             int on = 1;
307             setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
308             setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
309
310             if (connect(fd, addr->ai_addr, addr->ai_addrlen) >= 0)
311                 break;
312             close(fd);
313             fd = -1;
314         }
315     }
316     freeaddrinfo(results);
317     return fd;
318 }
319
320 #ifndef _WIN32
321 static int _xcb_open_unix(char *protocol, const char *file)
322 {
323     int fd;
324     struct sockaddr_un addr;
325
326     if (protocol && strcmp("unix",protocol))
327         return -1;
328
329     strcpy(addr.sun_path, file);
330     addr.sun_family = AF_UNIX;
331 #ifdef HAVE_SOCKADDR_SUN_LEN
332     addr.sun_len = SUN_LEN(&addr);
333 #endif
334     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
335     if(fd == -1)
336         return -1;
337     if(connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
338         close(fd);
339         return -1;
340     }
341     return fd;
342 }
343 #endif /* !_WIN32 */
344
345 #ifdef HAVE_ABSTRACT_SOCKETS
346 static int _xcb_open_abstract(char *protocol, const char *file, size_t filelen)
347 {
348     int fd;
349     struct sockaddr_un addr = {0};
350     socklen_t namelen;
351
352     if (protocol && strcmp("unix",protocol))
353         return -1;
354
355     strcpy(addr.sun_path + 1, file);
356     addr.sun_family = AF_UNIX;
357     namelen = offsetof(struct sockaddr_un, sun_path) + 1 + filelen;
358 #ifdef HAVE_SOCKADDR_SUN_LEN
359     addr.sun_len = 1 + filelen;
360 #endif
361     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
362     if (fd == -1)
363         return -1;
364     if (connect(fd, (struct sockaddr *) &addr, namelen) == -1) {
365         close(fd);
366         return -1;
367     }
368     return fd;
369 }
370 #endif
371
372 xcb_connection_t *xcb_connect(const char *displayname, int *screenp)
373 {
374     return xcb_connect_to_display_with_auth_info(displayname, NULL, screenp);
375 }
376
377 xcb_connection_t *xcb_connect_to_display_with_auth_info(const char *displayname, xcb_auth_info_t *auth, int *screenp)
378 {
379     int fd, display = 0;
380     char *host = NULL;
381     char *protocol = NULL;
382     xcb_auth_info_t ourauth;
383     xcb_connection_t *c;
384
385     int parsed = _xcb_parse_display(displayname, &host, &protocol, &display, screenp);
386     
387     if(!parsed) {
388         c = (xcb_connection_t *) &error_connection;
389         goto out;
390     } else
391         fd = _xcb_open(host, protocol, display);
392
393     if(fd == -1) {
394         c = (xcb_connection_t *) &error_connection;
395         goto out;
396     }
397
398     if(auth) {
399         c = xcb_connect_to_fd(fd, auth);
400         goto out;
401     }
402
403     if(_xcb_get_auth_info(fd, &ourauth, display))
404     {
405         c = xcb_connect_to_fd(fd, &ourauth);
406         free(ourauth.name);
407         free(ourauth.data);
408     }
409     else
410         c = xcb_connect_to_fd(fd, 0);
411
412 out:
413     free(host);
414     free(protocol);
415     return c;
416 }