Merge branch 'gsoc2010' of git://anongit.freedesktop.org/~chr/libxcb
[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 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 DNETCONN
161 static int _xcb_open_decnet(const char *host, char *protocol, const unsigned short port);
162 #endif
163 #ifdef HAVE_ABSTRACT_SOCKETS
164 static int _xcb_open_abstract(char *protocol, const char *file, size_t filelen);
165 #endif
166
167 static int _xcb_open(const char *host, char *protocol, const int display)
168 {
169     int fd;
170     static const char unix_base[] = "/tmp/.X11-unix/X";
171     const char *base = unix_base;
172     size_t filelen;
173     char *file = NULL;
174     int actual_filelen;
175
176 #ifdef HAVE_LAUNCHD
177         if(strncmp(host, "/tmp/launch", 11) == 0) {
178                 base = host;
179                 host = "";
180                 protocol = NULL;
181         }
182 #endif
183
184     if(*host || protocol)
185     {
186 #ifdef DNETCONN
187         /* DECnet displays have two colons, so _xcb_parse_display will have
188            left one at the end.  However, an IPv6 address can end with *two*
189            colons, so only treat this as a DECnet display if host ends with
190            exactly one colon. */
191         char *colon = strchr(host, ':');
192         if(colon && *(colon+1) == '\0')
193         {
194             *colon = '\0';
195             return _xcb_open_decnet(host, protocol, display);
196         }
197         else
198 #endif
199             if (protocol
200                 || strcmp("unix",host)) { /* follow the old unix: rule */
201
202                 /* display specifies TCP */
203                 unsigned short port = X_TCP_PORT + display;
204                 return _xcb_open_tcp(host, protocol, port);
205             }
206     }
207
208 #ifndef _WIN32
209     filelen = strlen(base) + 1 + sizeof(display) * 3 + 1;
210     file = malloc(filelen);
211     if(file == NULL)
212         return -1;
213
214     /* display specifies Unix socket */
215 #ifdef HAVE_LAUNCHD
216     if(strncmp(base, "/tmp/launch", 11) == 0)
217         actual_filelen = snprintf(file, filelen, "%s:%d", base, display);
218     else
219 #endif
220         actual_filelen = snprintf(file, filelen, "%s%d", base, display);
221     if(actual_filelen < 0)
222     {
223         free(file);
224         return -1;
225     }
226     /* snprintf may truncate the file */
227     filelen = MIN(actual_filelen, filelen - 1);
228 #ifdef HAVE_ABSTRACT_SOCKETS
229     fd = _xcb_open_abstract(protocol, file, filelen);
230     if (fd >= 0 || (errno != ENOENT && errno != ECONNREFUSED))
231     {
232         free(file);
233         return fd;
234     }
235
236 #endif
237     fd = _xcb_open_unix(protocol, file);
238     free(file);
239
240     return fd;
241 #endif /* !_WIN32 */
242     return -1; /* if control reaches here then something has gone wrong */
243 }
244
245 static int _xcb_socket(int family, int type, int proto)
246 {
247     int fd;
248
249 #ifdef SOCK_CLOEXEC
250     fd = socket(family, type | SOCK_CLOEXEC, proto);
251     if (fd == -1 && errno == EINVAL)
252 #endif
253     {
254         fd = socket(family, type, proto);
255 #ifndef _WIN32
256         if (fd >= 0)
257             fcntl(fd, F_SETFD, FD_CLOEXEC);
258 #endif
259     }
260     return fd;
261 }
262
263 #ifdef DNETCONN
264 static int _xcb_open_decnet(const char *host, const char *protocol, const unsigned short port)
265 {
266     int fd;
267     struct sockaddr_dn addr;
268     struct accessdata_dn accessdata;
269     struct nodeent *nodeaddr = getnodebyname(host);
270
271     if(!nodeaddr)
272         return -1;
273     if (protocol && strcmp("dnet",protocol))
274         return -1;
275     addr.sdn_family = AF_DECnet;
276
277     addr.sdn_add.a_len = nodeaddr->n_length;
278     memcpy(addr.sdn_add.a_addr, nodeaddr->n_addr, addr.sdn_add.a_len);
279
280     addr.sdn_objnamel = sprintf((char *)addr.sdn_objname, "X$X%d", port);
281     if(addr.sdn_objnamel < 0)
282         return -1;
283     addr.sdn_objnum = 0;
284
285     fd = _xcb_socket(PF_DECnet, SOCK_STREAM, 0);
286     if(fd == -1)
287         return -1;
288
289     memset(&accessdata, 0, sizeof(accessdata));
290     accessdata.acc_accl = sprintf((char*)accessdata.acc_acc, "%d", getuid());
291     if(accessdata.acc_accl < 0)
292         return -1;
293     setsockopt(fd, DNPROTO_NSP, SO_CONACCESS, &accessdata, sizeof(accessdata));
294
295     if(connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
296         close(fd);
297         return -1;
298     }
299     return fd;
300 }
301 #endif
302
303 static int _xcb_open_tcp(const char *host, char *protocol, const unsigned short port)
304 {
305     int fd = -1;
306     struct addrinfo hints;
307     char service[6]; /* "65535" with the trailing '\0' */
308     struct addrinfo *results, *addr;
309     char *bracket;
310
311     if (protocol && strcmp("tcp",protocol) && strcmp("inet",protocol)
312 #ifdef AF_INET6
313                  && strcmp("inet6",protocol)
314 #endif
315         )
316         return -1;
317         
318     if (*host == '\0')
319         host = "localhost";
320
321     memset(&hints, 0, sizeof(hints));
322 #ifdef AI_ADDRCONFIG
323     hints.ai_flags |= AI_ADDRCONFIG;
324 #endif
325 #ifdef AI_NUMERICSERV
326     hints.ai_flags |= AI_NUMERICSERV;
327 #endif
328     hints.ai_family = AF_UNSPEC;
329     hints.ai_socktype = SOCK_STREAM;
330
331 #ifdef AF_INET6
332     /* Allow IPv6 addresses enclosed in brackets. */
333     if(host[0] == '[' && (bracket = strrchr(host, ']')) && bracket[1] == '\0')
334     {
335         *bracket = '\0';
336         ++host;
337         hints.ai_flags |= AI_NUMERICHOST;
338         hints.ai_family = AF_INET6;
339     }
340 #endif
341
342     snprintf(service, sizeof(service), "%hu", port);
343     if(getaddrinfo(host, service, &hints, &results))
344         /* FIXME: use gai_strerror, and fill in error connection */
345         return -1;
346
347     for(addr = results; addr; addr = addr->ai_next)
348     {
349         fd = _xcb_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
350         if(fd >= 0) {
351             int on = 1;
352             setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
353             setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
354
355             if (connect(fd, addr->ai_addr, addr->ai_addrlen) >= 0)
356                 break;
357             close(fd);
358             fd = -1;
359         }
360     }
361     freeaddrinfo(results);
362     return fd;
363 }
364
365 #ifndef _WIN32
366 static int _xcb_open_unix(char *protocol, const char *file)
367 {
368     int fd;
369     struct sockaddr_un addr;
370
371     if (protocol && strcmp("unix",protocol))
372         return -1;
373
374     strcpy(addr.sun_path, file);
375     addr.sun_family = AF_UNIX;
376 #ifdef HAVE_SOCKADDR_SUN_LEN
377     addr.sun_len = SUN_LEN(&addr);
378 #endif
379     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
380     if(fd == -1)
381         return -1;
382     if(connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
383         close(fd);
384         return -1;
385     }
386     return fd;
387 }
388 #endif /* !_WIN32 */
389
390 #ifdef HAVE_ABSTRACT_SOCKETS
391 static int _xcb_open_abstract(char *protocol, const char *file, size_t filelen)
392 {
393     int fd;
394     struct sockaddr_un addr = {0};
395     socklen_t namelen;
396
397     if (protocol && strcmp("unix",protocol))
398         return -1;
399
400     strcpy(addr.sun_path + 1, file);
401     addr.sun_family = AF_UNIX;
402     namelen = offsetof(struct sockaddr_un, sun_path) + 1 + filelen;
403 #ifdef HAVE_SOCKADDR_SUN_LEN
404     addr.sun_len = 1 + filelen;
405 #endif
406     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
407     if (fd == -1)
408         return -1;
409     if (connect(fd, (struct sockaddr *) &addr, namelen) == -1) {
410         close(fd);
411         return -1;
412     }
413     return fd;
414 }
415 #endif
416
417 xcb_connection_t *xcb_connect(const char *displayname, int *screenp)
418 {
419     return xcb_connect_to_display_with_auth_info(displayname, NULL, screenp);
420 }
421
422 xcb_connection_t *xcb_connect_to_display_with_auth_info(const char *displayname, xcb_auth_info_t *auth, int *screenp)
423 {
424     int fd, display = 0;
425     char *host = NULL;
426     char *protocol = NULL;
427     xcb_auth_info_t ourauth;
428     xcb_connection_t *c;
429
430     int parsed = _xcb_parse_display(displayname, &host, &protocol, &display, screenp);
431     
432     if(!parsed) {
433         c = (xcb_connection_t *) &error_connection;
434         goto out;
435     } else
436         fd = _xcb_open(host, protocol, display);
437
438     if(fd == -1) {
439         c = (xcb_connection_t *) &error_connection;
440         goto out;
441     }
442
443     if(auth) {
444         c = xcb_connect_to_fd(fd, auth);
445         goto out;
446     }
447
448     if(_xcb_get_auth_info(fd, &ourauth, display))
449     {
450         c = xcb_connect_to_fd(fd, &ourauth);
451         free(ourauth.name);
452         free(ourauth.data);
453     }
454     else
455         c = xcb_connect_to_fd(fd, 0);
456
457 out:
458     free(host);
459     free(protocol);
460     return c;
461 }