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