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