Merge branch 'master' of git://github.com/topcat/xcb-win32
[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 #ifdef DNETCONN
32 #include <netdnet/dnetdb.h>
33 #include <netdnet/dn.h>
34 #endif
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 <sys/socket.h>
46 #include <sys/un.h>
47 #include <netinet/in.h>
48 #include <netinet/tcp.h>
49 #include <fcntl.h>
50 #include <netdb.h>
51 #endif /* _WIN32 */
52
53 #include "xcb.h"
54 #include "xcbext.h"
55 #include "xcbint.h"
56
57 static const int error_connection = 1;
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 static int _xcb_parse_display(const char *name, char **host, char **protocol,
68                       int *displayp, int *screenp)
69 {
70     int len, display, screen;
71     char *slash, *colon, *dot, *end;
72
73     if(!name || !*name)
74         name = getenv("DISPLAY");
75     if(!name)
76         return 0;
77
78 #ifdef HAVE_LAUNCHD
79     if(strncmp(name, "/tmp/launch", 11) == 0)
80         slash = NULL;
81     else
82 #endif
83     slash = strrchr(name, '/');
84
85     if (slash) {
86         len = slash - name;
87         if (protocol) {
88             *protocol = malloc(len + 1);
89             if(!*protocol)
90                 return 0;
91             memcpy(*protocol, name, len);
92             (*protocol)[len] = '\0';
93         }
94         name = slash + 1;
95     } else
96         if (protocol)
97             *protocol = NULL;
98
99     colon = strrchr(name, ':');
100     if(!colon)
101         goto error_out;
102     len = colon - name;
103     ++colon;
104     display = strtoul(colon, &dot, 10);
105     if(dot == colon)
106         goto error_out;
107     if(*dot == '\0')
108         screen = 0;
109     else
110     {
111         if(*dot != '.')
112             goto error_out;
113         ++dot;
114         screen = strtoul(dot, &end, 10);
115         if(end == dot || *end != '\0')
116             goto error_out;
117     }
118     /* At this point, the display string is fully parsed and valid, but
119      * the caller's memory is untouched. */
120
121     *host = malloc(len + 1);
122     if(!*host)
123         goto error_out;
124     memcpy(*host, name, len);
125     (*host)[len] = '\0';
126     *displayp = display;
127     if(screenp)
128         *screenp = screen;
129     return 1;
130
131 error_out:
132     if (protocol) {
133         free(*protocol);
134         *protocol = NULL;
135     }
136
137     return 0;
138 }
139
140 int xcb_parse_display(const char *name, char **host, int *displayp,
141                              int *screenp)
142 {
143     return _xcb_parse_display(name, host, NULL, displayp, screenp);
144 }
145
146 static int _xcb_open_tcp(const char *host, char *protocol, const unsigned short port);
147 #ifndef _WIN32
148 static int _xcb_open_unix(char *protocol, const char *file);
149 #endif /* !WIN32 */
150 #ifdef DNETCONN
151 static int _xcb_open_decnet(const char *host, char *protocol, const unsigned short port);
152 #endif
153 #ifdef HAVE_ABSTRACT_SOCKETS
154 static int _xcb_open_abstract(char *protocol, const char *file, size_t filelen);
155 #endif
156
157 static int _xcb_open(const char *host, char *protocol, const int display)
158 {
159     int fd;
160     static const char unix_base[] = "/tmp/.X11-unix/X";
161     const char *base = unix_base;
162     size_t filelen;
163     char *file = NULL;
164     int actual_filelen;
165
166 #ifdef HAVE_LAUNCHD
167         if(strncmp(host, "/tmp/launch", 11) == 0) {
168                 base = host;
169                 host = "";
170                 protocol = NULL;
171         }
172 #endif
173
174     if(*host || protocol)
175     {
176 #ifdef DNETCONN
177         /* DECnet displays have two colons, so _xcb_parse_display will have
178            left one at the end.  However, an IPv6 address can end with *two*
179            colons, so only treat this as a DECnet display if host ends with
180            exactly one colon. */
181         char *colon = strchr(host, ':');
182         if(colon && *(colon+1) == '\0')
183         {
184             *colon = '\0';
185             return _xcb_open_decnet(host, protocol, display);
186         }
187         else
188 #endif
189             if (protocol
190                 || strcmp("unix",host)) { /* follow the old unix: rule */
191
192                 /* display specifies TCP */
193                 unsigned short port = X_TCP_PORT + display;
194                 return _xcb_open_tcp(host, protocol, port);
195             }
196     }
197
198 #ifndef _WIN32
199     filelen = strlen(base) + 1 + sizeof(display) * 3 + 1;
200     file = malloc(filelen);
201     if(file == NULL)
202         return -1;
203
204     /* display specifies Unix socket */
205 #ifdef HAVE_LAUNCHD
206     if(strncmp(base, "/tmp/launch", 11) == 0)
207         actual_filelen = snprintf(file, filelen, "%s:%d", base, display);
208     else
209 #endif
210         actual_filelen = snprintf(file, filelen, "%s%d", base, display);
211     if(actual_filelen < 0)
212     {
213         free(file);
214         return -1;
215     }
216     /* snprintf may truncate the file */
217     filelen = MIN(actual_filelen, filelen - 1);
218 #ifdef HAVE_ABSTRACT_SOCKETS
219     fd = _xcb_open_abstract(protocol, file, filelen);
220     if (fd >= 0 || (errno != ENOENT && errno != ECONNREFUSED))
221     {
222         free(file);
223         return fd;
224     }
225
226 #endif
227     fd = _xcb_open_unix(protocol, file);
228     free(file);
229
230     return fd;
231 #endif /* !_WIN32 */
232     return -1; /* if control reaches here then something has gone wrong */
233 }
234
235 static int _xcb_socket(int family, int type, int proto)
236 {
237     int fd;
238
239 #ifdef SOCK_CLOEXEC
240     fd = socket(family, type | SOCK_CLOEXEC, proto);
241     if (fd == -1 && errno == EINVAL)
242 #endif
243     {
244         fd = socket(family, type, proto);
245 #ifndef _WIN32
246         if (fd >= 0)
247             fcntl(fd, F_SETFD, FD_CLOEXEC);
248 #endif
249     }
250     return fd;
251 }
252
253 #ifdef DNETCONN
254 static int _xcb_open_decnet(const char *host, const char *protocol, const unsigned short port)
255 {
256     int fd;
257     struct sockaddr_dn addr;
258     struct accessdata_dn accessdata;
259     struct nodeent *nodeaddr = getnodebyname(host);
260
261     if(!nodeaddr)
262         return -1;
263     if (protocol && strcmp("dnet",protocol))
264         return -1;
265     addr.sdn_family = AF_DECnet;
266
267     addr.sdn_add.a_len = nodeaddr->n_length;
268     memcpy(addr.sdn_add.a_addr, nodeaddr->n_addr, addr.sdn_add.a_len);
269
270     addr.sdn_objnamel = sprintf((char *)addr.sdn_objname, "X$X%d", port);
271     if(addr.sdn_objnamel < 0)
272         return -1;
273     addr.sdn_objnum = 0;
274
275     fd = _xcb_socket(PF_DECnet, SOCK_STREAM, 0);
276     if(fd == -1)
277         return -1;
278
279     memset(&accessdata, 0, sizeof(accessdata));
280     accessdata.acc_accl = sprintf((char*)accessdata.acc_acc, "%d", getuid());
281     if(accessdata.acc_accl < 0)
282         return -1;
283     setsockopt(fd, DNPROTO_NSP, SO_CONACCESS, &accessdata, sizeof(accessdata));
284
285     if(connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
286         close(fd);
287         return -1;
288     }
289     return fd;
290 }
291 #endif
292
293 static int _xcb_open_tcp(const char *host, char *protocol, const unsigned short port)
294 {
295     int fd = -1;
296     struct addrinfo hints;
297     char service[6]; /* "65535" with the trailing '\0' */
298     struct addrinfo *results, *addr;
299     char *bracket;
300
301     if (protocol && strcmp("tcp",protocol) && strcmp("inet",protocol)
302 #ifdef AF_INET6
303                  && strcmp("inet6",protocol)
304 #endif
305         )
306         return -1;
307         
308     if (*host == '\0')
309         host = "localhost";
310
311     memset(&hints, 0, sizeof(hints));
312 #ifdef AI_ADDRCONFIG
313     hints.ai_flags |= AI_ADDRCONFIG;
314 #endif
315 #ifdef AI_NUMERICSERV
316     hints.ai_flags |= AI_NUMERICSERV;
317 #endif
318     hints.ai_family = AF_UNSPEC;
319     hints.ai_socktype = SOCK_STREAM;
320
321 #ifdef AF_INET6
322     /* Allow IPv6 addresses enclosed in brackets. */
323     if(host[0] == '[' && (bracket = strrchr(host, ']')) && bracket[1] == '\0')
324     {
325         *bracket = '\0';
326         ++host;
327         hints.ai_flags |= AI_NUMERICHOST;
328         hints.ai_family = AF_INET6;
329     }
330 #endif
331
332     snprintf(service, sizeof(service), "%hu", port);
333     if(getaddrinfo(host, service, &hints, &results))
334         /* FIXME: use gai_strerror, and fill in error connection */
335         return -1;
336
337     for(addr = results; addr; addr = addr->ai_next)
338     {
339         fd = _xcb_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
340         if(fd >= 0) {
341             int on = 1;
342             setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
343             setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
344
345             if (connect(fd, addr->ai_addr, addr->ai_addrlen) >= 0)
346                 break;
347             close(fd);
348             fd = -1;
349         }
350     }
351     freeaddrinfo(results);
352     return fd;
353 }
354
355 #ifndef _WIN32
356 static int _xcb_open_unix(char *protocol, const char *file)
357 {
358     int fd;
359     struct sockaddr_un addr;
360
361     if (protocol && strcmp("unix",protocol))
362         return -1;
363
364     strcpy(addr.sun_path, file);
365     addr.sun_family = AF_UNIX;
366 #ifdef HAVE_SOCKADDR_SUN_LEN
367     addr.sun_len = SUN_LEN(&addr);
368 #endif
369     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
370     if(fd == -1)
371         return -1;
372     if(connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
373         close(fd);
374         return -1;
375     }
376     return fd;
377 }
378 #endif /* !_WIN32 */
379
380 #ifdef HAVE_ABSTRACT_SOCKETS
381 static int _xcb_open_abstract(char *protocol, const char *file, size_t filelen)
382 {
383     int fd;
384     struct sockaddr_un addr = {0};
385     socklen_t namelen;
386
387     if (protocol && strcmp("unix",protocol))
388         return -1;
389
390     strcpy(addr.sun_path + 1, file);
391     addr.sun_family = AF_UNIX;
392     namelen = offsetof(struct sockaddr_un, sun_path) + 1 + filelen;
393 #ifdef HAVE_SOCKADDR_SUN_LEN
394     addr.sun_len = 1 + filelen;
395 #endif
396     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
397     if (fd == -1)
398         return -1;
399     if (connect(fd, (struct sockaddr *) &addr, namelen) == -1) {
400         close(fd);
401         return -1;
402     }
403     return fd;
404 }
405 #endif
406
407 xcb_connection_t *xcb_connect(const char *displayname, int *screenp)
408 {
409     return xcb_connect_to_display_with_auth_info(displayname, NULL, screenp);
410 }
411
412 xcb_connection_t *xcb_connect_to_display_with_auth_info(const char *displayname, xcb_auth_info_t *auth, int *screenp)
413 {
414     int fd, display = 0;
415     char *host = NULL;
416     char *protocol = NULL;
417     xcb_auth_info_t ourauth;
418     xcb_connection_t *c;
419
420     int parsed = _xcb_parse_display(displayname, &host, &protocol, &display, screenp);
421     
422     if(!parsed) {
423         c = (xcb_connection_t *) &error_connection;
424         goto out;
425     } else
426         fd = _xcb_open(host, protocol, display);
427
428     if(fd == -1) {
429         c = (xcb_connection_t *) &error_connection;
430         goto out;
431     }
432
433     if(auth) {
434         c = xcb_connect_to_fd(fd, auth);
435         goto out;
436     }
437
438     if(_xcb_get_auth_info(fd, &ourauth, display))
439     {
440         c = xcb_connect_to_fd(fd, &ourauth);
441         free(ourauth.name);
442         free(ourauth.data);
443     }
444     else
445         c = xcb_connect_to_fd(fd, 0);
446
447 out:
448     free(host);
449     free(protocol);
450     return c;
451 }