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