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