Merge branch 'master' of git://anongit.freedesktop.org/~peterh/libxcb
[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 #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 int xcb_popcount(uint32_t mask)
58 {
59     uint32_t y;
60     y = (mask >> 1) & 033333333333;
61     y = mask - y - ((y >> 1) & 033333333333);
62     return ((y + (y >> 3)) & 030707070707) % 077;
63 }
64
65 int xcb_sumof(uint8_t *list, int len)
66 {
67   int i, s = 0;
68   for(i=0; i<len; i++) {
69     s += *list;
70     list++;
71   }
72   return s;
73 }
74
75 static int _xcb_parse_display(const char *name, char **host, char **protocol,
76                       int *displayp, int *screenp)
77 {
78     int len, display, screen;
79     char *slash, *colon, *dot, *end;
80
81     if(!name || !*name)
82         name = getenv("DISPLAY");
83     if(!name)
84         return 0;
85
86 #ifdef HAVE_LAUNCHD
87     if(strncmp(name, "/tmp/launch", 11) == 0)
88         slash = NULL;
89     else
90 #endif
91     slash = strrchr(name, '/');
92
93     if (slash) {
94         len = slash - name;
95         if (protocol) {
96             *protocol = malloc(len + 1);
97             if(!*protocol)
98                 return 0;
99             memcpy(*protocol, name, len);
100             (*protocol)[len] = '\0';
101         }
102         name = slash + 1;
103     } else
104         if (protocol)
105             *protocol = NULL;
106
107     colon = strrchr(name, ':');
108     if(!colon)
109         goto error_out;
110     len = colon - name;
111     ++colon;
112     display = strtoul(colon, &dot, 10);
113     if(dot == colon)
114         goto error_out;
115     if(*dot == '\0')
116         screen = 0;
117     else
118     {
119         if(*dot != '.')
120             goto error_out;
121         ++dot;
122         screen = strtoul(dot, &end, 10);
123         if(end == dot || *end != '\0')
124             goto error_out;
125     }
126     /* At this point, the display string is fully parsed and valid, but
127      * the caller's memory is untouched. */
128
129     *host = malloc(len + 1);
130     if(!*host)
131         goto error_out;
132     memcpy(*host, name, len);
133     (*host)[len] = '\0';
134     *displayp = display;
135     if(screenp)
136         *screenp = screen;
137     return 1;
138
139 error_out:
140     if (protocol) {
141         free(*protocol);
142         *protocol = NULL;
143     }
144
145     return 0;
146 }
147
148 int xcb_parse_display(const char *name, char **host, int *displayp,
149                              int *screenp)
150 {
151     return _xcb_parse_display(name, host, NULL, displayp, screenp);
152 }
153
154 static int _xcb_open_tcp(const char *host, char *protocol, const unsigned short port);
155 #ifndef _WIN32
156 static int _xcb_open_unix(char *protocol, const char *file);
157 #endif /* !WIN32 */
158 #ifdef DNETCONN
159 static int _xcb_open_decnet(const char *host, char *protocol, const unsigned short port);
160 #endif
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(*host || protocol)
183     {
184 #ifdef DNETCONN
185         /* DECnet displays have two colons, so _xcb_parse_display will have
186            left one at the end.  However, an IPv6 address can end with *two*
187            colons, so only treat this as a DECnet display if host ends with
188            exactly one colon. */
189         char *colon = strchr(host, ':');
190         if(colon && *(colon+1) == '\0')
191         {
192             *colon = '\0';
193             return _xcb_open_decnet(host, protocol, display);
194         }
195         else
196 #endif
197             if (protocol
198                 || strcmp("unix",host)) { /* follow the old unix: rule */
199
200                 /* display specifies TCP */
201                 unsigned short port = X_TCP_PORT + display;
202                 return _xcb_open_tcp(host, protocol, port);
203             }
204     }
205
206 #ifndef _WIN32
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 #ifdef DNETCONN
262 static int _xcb_open_decnet(const char *host, const char *protocol, const unsigned short port)
263 {
264     int fd;
265     struct sockaddr_dn addr;
266     struct accessdata_dn accessdata;
267     struct nodeent *nodeaddr = getnodebyname(host);
268
269     if(!nodeaddr)
270         return -1;
271     if (protocol && strcmp("dnet",protocol))
272         return -1;
273     addr.sdn_family = AF_DECnet;
274
275     addr.sdn_add.a_len = nodeaddr->n_length;
276     memcpy(addr.sdn_add.a_addr, nodeaddr->n_addr, addr.sdn_add.a_len);
277
278     addr.sdn_objnamel = sprintf((char *)addr.sdn_objname, "X$X%d", port);
279     if(addr.sdn_objnamel < 0)
280         return -1;
281     addr.sdn_objnum = 0;
282
283     fd = _xcb_socket(PF_DECnet, SOCK_STREAM, 0);
284     if(fd == -1)
285         return -1;
286
287     memset(&accessdata, 0, sizeof(accessdata));
288     accessdata.acc_accl = sprintf((char*)accessdata.acc_acc, "%d", getuid());
289     if(accessdata.acc_accl < 0)
290         return -1;
291     setsockopt(fd, DNPROTO_NSP, SO_CONACCESS, &accessdata, sizeof(accessdata));
292
293     if(connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
294         close(fd);
295         return -1;
296     }
297     return fd;
298 }
299 #endif
300
301 static int _xcb_open_tcp(const char *host, char *protocol, const unsigned short port)
302 {
303     int fd = -1;
304     struct addrinfo hints;
305     char service[6]; /* "65535" with the trailing '\0' */
306     struct addrinfo *results, *addr;
307     char *bracket;
308
309     if (protocol && strcmp("tcp",protocol) && strcmp("inet",protocol)
310 #ifdef AF_INET6
311                  && strcmp("inet6",protocol)
312 #endif
313         )
314         return -1;
315         
316     if (*host == '\0')
317         host = "localhost";
318
319     memset(&hints, 0, sizeof(hints));
320 #ifdef AI_ADDRCONFIG
321     hints.ai_flags |= AI_ADDRCONFIG;
322 #endif
323 #ifdef AI_NUMERICSERV
324     hints.ai_flags |= AI_NUMERICSERV;
325 #endif
326     hints.ai_family = AF_UNSPEC;
327     hints.ai_socktype = SOCK_STREAM;
328
329 #ifdef AF_INET6
330     /* Allow IPv6 addresses enclosed in brackets. */
331     if(host[0] == '[' && (bracket = strrchr(host, ']')) && bracket[1] == '\0')
332     {
333         *bracket = '\0';
334         ++host;
335         hints.ai_flags |= AI_NUMERICHOST;
336         hints.ai_family = AF_INET6;
337     }
338 #endif
339
340     snprintf(service, sizeof(service), "%hu", port);
341     if(getaddrinfo(host, service, &hints, &results))
342         /* FIXME: use gai_strerror, and fill in error connection */
343         return -1;
344
345     for(addr = results; addr; addr = addr->ai_next)
346     {
347         fd = _xcb_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
348         if(fd >= 0) {
349             int on = 1;
350             setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
351             setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
352
353             if (connect(fd, addr->ai_addr, addr->ai_addrlen) >= 0)
354                 break;
355             close(fd);
356             fd = -1;
357         }
358     }
359     freeaddrinfo(results);
360     return fd;
361 }
362
363 #ifndef _WIN32
364 static int _xcb_open_unix(char *protocol, const char *file)
365 {
366     int fd;
367     struct sockaddr_un addr;
368
369     if (protocol && strcmp("unix",protocol))
370         return -1;
371
372     strcpy(addr.sun_path, file);
373     addr.sun_family = AF_UNIX;
374 #ifdef HAVE_SOCKADDR_SUN_LEN
375     addr.sun_len = SUN_LEN(&addr);
376 #endif
377     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
378     if(fd == -1)
379         return -1;
380     if(connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
381         close(fd);
382         return -1;
383     }
384     return fd;
385 }
386 #endif /* !_WIN32 */
387
388 #ifdef HAVE_ABSTRACT_SOCKETS
389 static int _xcb_open_abstract(char *protocol, const char *file, size_t filelen)
390 {
391     int fd;
392     struct sockaddr_un addr = {0};
393     socklen_t namelen;
394
395     if (protocol && strcmp("unix",protocol))
396         return -1;
397
398     strcpy(addr.sun_path + 1, file);
399     addr.sun_family = AF_UNIX;
400     namelen = offsetof(struct sockaddr_un, sun_path) + 1 + filelen;
401 #ifdef HAVE_SOCKADDR_SUN_LEN
402     addr.sun_len = 1 + filelen;
403 #endif
404     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
405     if (fd == -1)
406         return -1;
407     if (connect(fd, (struct sockaddr *) &addr, namelen) == -1) {
408         close(fd);
409         return -1;
410     }
411     return fd;
412 }
413 #endif
414
415 xcb_connection_t *xcb_connect(const char *displayname, int *screenp)
416 {
417     return xcb_connect_to_display_with_auth_info(displayname, NULL, screenp);
418 }
419
420 xcb_connection_t *xcb_connect_to_display_with_auth_info(const char *displayname, xcb_auth_info_t *auth, int *screenp)
421 {
422     int fd, display = 0;
423     char *host = NULL;
424     char *protocol = NULL;
425     xcb_auth_info_t ourauth;
426     xcb_connection_t *c;
427
428     int parsed = _xcb_parse_display(displayname, &host, &protocol, &display, screenp);
429     
430     if(!parsed) {
431         c = (xcb_connection_t *) &error_connection;
432         goto out;
433     } else
434         fd = _xcb_open(host, protocol, display);
435
436     if(fd == -1) {
437         c = (xcb_connection_t *) &error_connection;
438         goto out;
439     }
440
441     if(auth) {
442         c = xcb_connect_to_fd(fd, auth);
443         goto out;
444     }
445
446     if(_xcb_get_auth_info(fd, &ourauth, display))
447     {
448         c = xcb_connect_to_fd(fd, &ourauth);
449         free(ourauth.name);
450         free(ourauth.data);
451     }
452     else
453         c = xcb_connect_to_fd(fd, 0);
454
455 out:
456     free(host);
457     free(protocol);
458     return c;
459 }