ad9b3df7c9e693112ad9f922a3d67c7d072d7b74
[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(*host || protocol)
182     {
183         if (protocol
184             || strcmp("unix",host)) { /* follow the old unix: rule */
185
186             /* display specifies TCP */
187             unsigned short port = X_TCP_PORT + display;
188             return _xcb_open_tcp(host, protocol, port);
189         }
190     }
191
192 #ifndef _WIN32
193 #if defined(HAVE_TSOL_LABEL_H) && defined(HAVE_IS_SYSTEM_LABELED)
194     /* Check special path for Unix sockets under Solaris Trusted Extensions */
195     if (is_system_labeled())
196     {
197         struct stat sbuf;
198         const char *tsol_base = "/var/tsol/doors/.X11-unix/X";
199         char tsol_socket[PATH_MAX];
200
201         snprintf(tsol_socket, sizeof(tsol_socket), "%s%d", tsol_base, display);
202
203         if (stat(tsol_socket, &sbuf) == 0)
204             base = tsol_base;
205     }
206 #endif
207
208     filelen = strlen(base) + 1 + sizeof(display) * 3 + 1;
209     file = malloc(filelen);
210     if(file == NULL)
211         return -1;
212
213     /* display specifies Unix socket */
214 #ifdef HAVE_LAUNCHD
215     if(strncmp(base, "/tmp/launch", 11) == 0)
216         actual_filelen = snprintf(file, filelen, "%s:%d", base, display);
217     else
218 #endif
219         actual_filelen = snprintf(file, filelen, "%s%d", base, display);
220     if(actual_filelen < 0)
221     {
222         free(file);
223         return -1;
224     }
225     /* snprintf may truncate the file */
226     filelen = MIN(actual_filelen, filelen - 1);
227 #ifdef HAVE_ABSTRACT_SOCKETS
228     fd = _xcb_open_abstract(protocol, file, filelen);
229     if (fd >= 0 || (errno != ENOENT && errno != ECONNREFUSED))
230     {
231         free(file);
232         return fd;
233     }
234
235 #endif
236     fd = _xcb_open_unix(protocol, file);
237     free(file);
238
239     return fd;
240 #endif /* !_WIN32 */
241     return -1; /* if control reaches here then something has gone wrong */
242 }
243
244 static int _xcb_socket(int family, int type, int proto)
245 {
246     int fd;
247
248 #ifdef SOCK_CLOEXEC
249     fd = socket(family, type | SOCK_CLOEXEC, proto);
250     if (fd == -1 && errno == EINVAL)
251 #endif
252     {
253         fd = socket(family, type, proto);
254 #ifndef _WIN32
255         if (fd >= 0)
256             fcntl(fd, F_SETFD, FD_CLOEXEC);
257 #endif
258     }
259     return fd;
260 }
261
262
263 static int _xcb_open_tcp(const char *host, char *protocol, const unsigned short port)
264 {
265     int fd = -1;
266     struct addrinfo hints;
267     char service[6]; /* "65535" with the trailing '\0' */
268     struct addrinfo *results, *addr;
269     char *bracket;
270
271     if (protocol && strcmp("tcp",protocol) && strcmp("inet",protocol)
272 #ifdef AF_INET6
273                  && strcmp("inet6",protocol)
274 #endif
275         )
276         return -1;
277         
278     if (*host == '\0')
279         host = "localhost";
280
281     memset(&hints, 0, sizeof(hints));
282 #ifdef AI_ADDRCONFIG
283     hints.ai_flags |= AI_ADDRCONFIG;
284 #endif
285 #ifdef AI_NUMERICSERV
286     hints.ai_flags |= AI_NUMERICSERV;
287 #endif
288     hints.ai_family = AF_UNSPEC;
289     hints.ai_socktype = SOCK_STREAM;
290
291 #ifdef AF_INET6
292     /* Allow IPv6 addresses enclosed in brackets. */
293     if(host[0] == '[' && (bracket = strrchr(host, ']')) && bracket[1] == '\0')
294     {
295         *bracket = '\0';
296         ++host;
297         hints.ai_flags |= AI_NUMERICHOST;
298         hints.ai_family = AF_INET6;
299     }
300 #endif
301
302     snprintf(service, sizeof(service), "%hu", port);
303     if(getaddrinfo(host, service, &hints, &results))
304         /* FIXME: use gai_strerror, and fill in error connection */
305         return -1;
306
307     for(addr = results; addr; addr = addr->ai_next)
308     {
309         fd = _xcb_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
310         if(fd >= 0) {
311             int on = 1;
312             setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
313             setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
314
315             if (connect(fd, addr->ai_addr, addr->ai_addrlen) >= 0)
316                 break;
317             close(fd);
318             fd = -1;
319         }
320     }
321     freeaddrinfo(results);
322     return fd;
323 }
324
325 #ifndef _WIN32
326 static int _xcb_open_unix(char *protocol, const char *file)
327 {
328     int fd;
329     struct sockaddr_un addr;
330
331     if (protocol && strcmp("unix",protocol))
332         return -1;
333
334     strcpy(addr.sun_path, file);
335     addr.sun_family = AF_UNIX;
336 #ifdef HAVE_SOCKADDR_SUN_LEN
337     addr.sun_len = SUN_LEN(&addr);
338 #endif
339     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
340     if(fd == -1)
341         return -1;
342     if(connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
343         close(fd);
344         return -1;
345     }
346     return fd;
347 }
348 #endif /* !_WIN32 */
349
350 #ifdef HAVE_ABSTRACT_SOCKETS
351 static int _xcb_open_abstract(char *protocol, const char *file, size_t filelen)
352 {
353     int fd;
354     struct sockaddr_un addr = {0};
355     socklen_t namelen;
356
357     if (protocol && strcmp("unix",protocol))
358         return -1;
359
360     strcpy(addr.sun_path + 1, file);
361     addr.sun_family = AF_UNIX;
362     namelen = offsetof(struct sockaddr_un, sun_path) + 1 + filelen;
363 #ifdef HAVE_SOCKADDR_SUN_LEN
364     addr.sun_len = 1 + filelen;
365 #endif
366     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
367     if (fd == -1)
368         return -1;
369     if (connect(fd, (struct sockaddr *) &addr, namelen) == -1) {
370         close(fd);
371         return -1;
372     }
373     return fd;
374 }
375 #endif
376
377 xcb_connection_t *xcb_connect(const char *displayname, int *screenp)
378 {
379     return xcb_connect_to_display_with_auth_info(displayname, NULL, screenp);
380 }
381
382 xcb_connection_t *xcb_connect_to_display_with_auth_info(const char *displayname, xcb_auth_info_t *auth, int *screenp)
383 {
384     int fd, display = 0;
385     char *host = NULL;
386     char *protocol = NULL;
387     xcb_auth_info_t ourauth;
388     xcb_connection_t *c;
389
390     int parsed = _xcb_parse_display(displayname, &host, &protocol, &display, screenp);
391     
392     if(!parsed) {
393         c = (xcb_connection_t *) &error_connection;
394         goto out;
395     } else
396         fd = _xcb_open(host, protocol, display);
397
398     if(fd == -1) {
399         c = (xcb_connection_t *) &error_connection;
400         goto out;
401     }
402
403     if(auth) {
404         c = xcb_connect_to_fd(fd, auth);
405         goto out;
406     }
407
408     if(_xcb_get_auth_info(fd, &ourauth, display))
409     {
410         c = xcb_connect_to_fd(fd, &ourauth);
411         free(ourauth.name);
412         free(ourauth.data);
413     }
414     else
415         c = xcb_connect_to_fd(fd, 0);
416
417 out:
418     free(host);
419     free(protocol);
420     return c;
421 }