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