Support pre-IPv6 systems (without getaddrinfo)
[profile/ivi/libxcb.git] / 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 #include <arpa/inet.h>
38
39 #ifdef _WIN32
40 #include "xcb_windefs.h"
41 #else
42 #include <sys/socket.h>
43 #include <sys/un.h>
44 #include <netinet/in.h>
45 #include <netinet/tcp.h>
46 #include <fcntl.h>
47 #include <netdb.h>
48 #endif /* _WIN32 */
49
50 #include "xcb.h"
51 #include "xcbext.h"
52 #include "xcbint.h"
53
54 /* must be after "xcbint.h" to get autoconf #defines */
55 #if defined(HAVE_TSOL_LABEL_H) && defined(HAVE_IS_SYSTEM_LABELED)
56 # include <tsol/label.h>
57 # include <sys/stat.h>
58 #endif
59
60 int xcb_popcount(uint32_t mask)
61 {
62     uint32_t y;
63     y = (mask >> 1) & 033333333333;
64     y = mask - y - ((y >> 1) & 033333333333);
65     return ((y + (y >> 3)) & 030707070707) % 077;
66 }
67
68 int xcb_sumof(uint8_t *list, int len)
69 {
70   int i, s = 0;
71   for(i=0; i<len; i++) {
72     s += *list;
73     list++;
74   }
75   return s;
76 }
77
78 static int _xcb_parse_display(const char *name, char **host, char **protocol,
79                       int *displayp, int *screenp)
80 {
81     int len, display, screen;
82     char *slash, *colon, *dot, *end;
83
84     if(!name || !*name)
85         name = getenv("DISPLAY");
86     if(!name)
87         return 0;
88
89 #ifdef HAVE_LAUNCHD
90     if(strncmp(name, "/tmp/launch", 11) == 0)
91         slash = NULL;
92     else
93 #endif
94     slash = strrchr(name, '/');
95
96     if (slash) {
97         len = slash - name;
98         if (protocol) {
99             *protocol = malloc(len + 1);
100             if(!*protocol)
101                 return 0;
102             memcpy(*protocol, name, len);
103             (*protocol)[len] = '\0';
104         }
105         name = slash + 1;
106     } else
107         if (protocol)
108             *protocol = NULL;
109
110     colon = strrchr(name, ':');
111     if(!colon)
112         goto error_out;
113     len = colon - name;
114     ++colon;
115     display = strtoul(colon, &dot, 10);
116     if(dot == colon)
117         goto error_out;
118     if(*dot == '\0')
119         screen = 0;
120     else
121     {
122         if(*dot != '.')
123             goto error_out;
124         ++dot;
125         screen = strtoul(dot, &end, 10);
126         if(end == dot || *end != '\0')
127             goto error_out;
128     }
129     /* At this point, the display string is fully parsed and valid, but
130      * the caller's memory is untouched. */
131
132     *host = malloc(len + 1);
133     if(!*host)
134         goto error_out;
135     memcpy(*host, name, len);
136     (*host)[len] = '\0';
137     *displayp = display;
138     if(screenp)
139         *screenp = screen;
140     return 1;
141
142 error_out:
143     if (protocol) {
144         free(*protocol);
145         *protocol = NULL;
146     }
147
148     return 0;
149 }
150
151 int xcb_parse_display(const char *name, char **host, int *displayp,
152                              int *screenp)
153 {
154     return _xcb_parse_display(name, host, NULL, displayp, screenp);
155 }
156
157 static int _xcb_open_tcp(const char *host, char *protocol, const unsigned short port);
158 #ifndef _WIN32
159 static int _xcb_open_unix(char *protocol, const char *file);
160 #endif /* !WIN32 */
161 #ifdef HAVE_ABSTRACT_SOCKETS
162 static int _xcb_open_abstract(char *protocol, const char *file, size_t filelen);
163 #endif
164
165 static int _xcb_open(const char *host, char *protocol, const int display)
166 {
167     int fd;
168     static const char unix_base[] = "/tmp/.X11-unix/X";
169     const char *base = unix_base;
170     size_t filelen;
171     char *file = NULL;
172     int actual_filelen;
173
174 #ifdef HAVE_LAUNCHD
175     if(strncmp(host, "/tmp/launch", 11) == 0) {
176         base = host;
177         host = "";
178         protocol = NULL;
179     }
180 #endif
181
182     /* If protocol or host is "unix", fall through to Unix socket code below */
183     if ((!protocol || (strcmp("unix",protocol) != 0)) &&
184         (*host != '\0') && (strcmp("unix",host) != 0))
185     {
186         /* display specifies TCP */
187         unsigned short port = X_TCP_PORT + display;
188         return _xcb_open_tcp(host, protocol, port);
189     }
190
191 #ifndef _WIN32
192 #if defined(HAVE_TSOL_LABEL_H) && defined(HAVE_IS_SYSTEM_LABELED)
193     /* Check special path for Unix sockets under Solaris Trusted Extensions */
194     if (is_system_labeled())
195     {
196         struct stat sbuf;
197         const char *tsol_base = "/var/tsol/doors/.X11-unix/X";
198         char tsol_socket[PATH_MAX];
199
200         snprintf(tsol_socket, sizeof(tsol_socket), "%s%d", tsol_base, display);
201
202         if (stat(tsol_socket, &sbuf) == 0)
203             base = tsol_base;
204     }
205 #endif
206
207     filelen = strlen(base) + 1 + sizeof(display) * 3 + 1;
208     file = malloc(filelen);
209     if(file == NULL)
210         return -1;
211
212     /* display specifies Unix socket */
213 #ifdef HAVE_LAUNCHD
214     if(strncmp(base, "/tmp/launch", 11) == 0)
215         actual_filelen = snprintf(file, filelen, "%s:%d", base, display);
216     else
217 #endif
218         actual_filelen = snprintf(file, filelen, "%s%d", base, display);
219     if(actual_filelen < 0)
220     {
221         free(file);
222         return -1;
223     }
224     /* snprintf may truncate the file */
225     filelen = MIN(actual_filelen, filelen - 1);
226 #ifdef HAVE_ABSTRACT_SOCKETS
227     fd = _xcb_open_abstract(protocol, file, filelen);
228     if (fd >= 0 || (errno != ENOENT && errno != ECONNREFUSED))
229     {
230         free(file);
231         return fd;
232     }
233
234 #endif
235     fd = _xcb_open_unix(protocol, file);
236     free(file);
237
238     return fd;
239 #endif /* !_WIN32 */
240     return -1; /* if control reaches here then something has gone wrong */
241 }
242
243 static int _xcb_socket(int family, int type, int proto)
244 {
245     int fd;
246
247 #ifdef SOCK_CLOEXEC
248     fd = socket(family, type | SOCK_CLOEXEC, proto);
249     if (fd == -1 && errno == EINVAL)
250 #endif
251     {
252         fd = socket(family, type, proto);
253 #ifndef _WIN32
254         if (fd >= 0)
255             fcntl(fd, F_SETFD, FD_CLOEXEC);
256 #endif
257     }
258     return fd;
259 }
260
261
262 static int _xcb_do_connect(int fd, const struct sockaddr* addr, int addrlen) {
263         int on = 1;
264
265         if(fd < 0)
266                 return -1;
267
268         setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
269         setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
270
271         return connect(fd, addr, addrlen);
272 }
273
274 static int _xcb_open_tcp(const char *host, char *protocol, const unsigned short port)
275 {
276     int fd = -1;
277 #if HAVE_GETADDRINFO
278     struct addrinfo hints;
279     char service[6]; /* "65535" with the trailing '\0' */
280     struct addrinfo *results, *addr;
281     char *bracket;
282 #endif
283
284     if (protocol && strcmp("tcp",protocol) && strcmp("inet",protocol)
285 #ifdef AF_INET6
286                  && strcmp("inet6",protocol)
287 #endif
288         )
289         return -1;
290         
291     if (*host == '\0')
292         host = "localhost";
293
294 #if HAVE_GETADDRINFO
295     memset(&hints, 0, sizeof(hints));
296 #ifdef AI_NUMERICSERV
297     hints.ai_flags |= AI_NUMERICSERV;
298 #endif
299     hints.ai_family = AF_UNSPEC;
300     hints.ai_socktype = SOCK_STREAM;
301
302 #ifdef AF_INET6
303     /* Allow IPv6 addresses enclosed in brackets. */
304     if(host[0] == '[' && (bracket = strrchr(host, ']')) && bracket[1] == '\0')
305     {
306         *bracket = '\0';
307         ++host;
308         hints.ai_flags |= AI_NUMERICHOST;
309         hints.ai_family = AF_INET6;
310     }
311 #endif
312
313     snprintf(service, sizeof(service), "%hu", port);
314     if(getaddrinfo(host, service, &hints, &results))
315         /* FIXME: use gai_strerror, and fill in error connection */
316         return -1;
317
318     for(addr = results; addr; addr = addr->ai_next)
319     {
320         fd = _xcb_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
321         if (_xcb_do_connect(fd, addr->ai_addr, addr->ai_addrlen) >= 0)
322             break;
323         close(fd);
324         fd = -1;
325     }
326     freeaddrinfo(results);
327     return fd;
328 #else
329     {
330         struct hostent* _h;
331         struct sockaddr_in _s;
332         struct in_addr ** _c;
333
334         if((_h = gethostbyname(host)) == NULL)
335             return -1;
336
337         _c = (struct in_addr**)_h->h_addr_list;
338         fd = -1;
339
340         while(*_c) {
341             _s.sin_family = AF_INET;
342             _s.sin_port = htons(port);
343             _s.sin_addr = *(*_c);
344
345             fd = _xcb_socket(_s.sin_family, SOCK_STREAM, 0);
346             if(_xcb_do_connect(fd, (struct sockaddr*)&_s, sizeof(_s)) >= 0)
347                 break;
348
349             close(fd);
350             fd = -1;
351             ++_c;
352         }
353
354         return fd;
355     }
356 #endif
357 }
358
359 #ifndef _WIN32
360 static int _xcb_open_unix(char *protocol, const char *file)
361 {
362     int fd;
363     struct sockaddr_un addr;
364
365     if (protocol && strcmp("unix",protocol))
366         return -1;
367
368     strcpy(addr.sun_path, file);
369     addr.sun_family = AF_UNIX;
370 #ifdef HAVE_SOCKADDR_SUN_LEN
371     addr.sun_len = SUN_LEN(&addr);
372 #endif
373     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
374     if(fd == -1)
375         return -1;
376     if(connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
377         close(fd);
378         return -1;
379     }
380     return fd;
381 }
382 #endif /* !_WIN32 */
383
384 #ifdef HAVE_ABSTRACT_SOCKETS
385 static int _xcb_open_abstract(char *protocol, const char *file, size_t filelen)
386 {
387     int fd;
388     struct sockaddr_un addr = {0};
389     socklen_t namelen;
390
391     if (protocol && strcmp("unix",protocol))
392         return -1;
393
394     strcpy(addr.sun_path + 1, file);
395     addr.sun_family = AF_UNIX;
396     namelen = offsetof(struct sockaddr_un, sun_path) + 1 + filelen;
397 #ifdef HAVE_SOCKADDR_SUN_LEN
398     addr.sun_len = 1 + filelen;
399 #endif
400     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
401     if (fd == -1)
402         return -1;
403     if (connect(fd, (struct sockaddr *) &addr, namelen) == -1) {
404         close(fd);
405         return -1;
406     }
407     return fd;
408 }
409 #endif
410
411 xcb_connection_t *xcb_connect(const char *displayname, int *screenp)
412 {
413     return xcb_connect_to_display_with_auth_info(displayname, NULL, screenp);
414 }
415
416 xcb_connection_t *xcb_connect_to_display_with_auth_info(const char *displayname, xcb_auth_info_t *auth, int *screenp)
417 {
418     int fd, display = 0;
419     char *host = NULL;
420     char *protocol = NULL;
421     xcb_auth_info_t ourauth;
422     xcb_connection_t *c;
423
424     int parsed = _xcb_parse_display(displayname, &host, &protocol, &display, screenp);
425     
426     if(!parsed) {
427         c = (xcb_connection_t *) &error_connection;
428         goto out;
429     } else
430         fd = _xcb_open(host, protocol, display);
431
432     if(fd == -1) {
433         c = (xcb_connection_t *) &error_connection;
434         goto out;
435     }
436
437     if(auth) {
438         c = xcb_connect_to_fd(fd, auth);
439         goto out;
440     }
441
442     if(_xcb_get_auth_info(fd, &ourauth, display))
443     {
444         c = xcb_connect_to_fd(fd, &ourauth);
445         free(ourauth.name);
446         free(ourauth.data);
447     }
448     else
449         c = xcb_connect_to_fd(fd, 0);
450
451 out:
452     free(host);
453     free(protocol);
454     return c;
455 }