xcb_open: Improve protocol/host parsing
[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     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(const 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(const char *host, char *protocol, const int display)
142 {
143     int fd;
144     static const char unix_base[] = "/tmp/.X11-unix/X";
145     const char *base = unix_base;
146     size_t filelen;
147     char *file = NULL;
148     int actual_filelen;
149
150 #ifdef HAVE_LAUNCHD
151         if(strncmp(host, "/tmp/launch", 11) == 0) {
152                 base = host;
153                 host = "";
154                 protocol = NULL;
155         }
156 #endif
157
158     if(*host || protocol)
159     {
160 #ifdef DNETCONN
161         /* DECnet displays have two colons, so _xcb_parse_display will have
162            left one at the end.  However, an IPv6 address can end with *two*
163            colons, so only treat this as a DECnet display if host ends with
164            exactly one colon. */
165         char *colon = strchr(host, ':');
166         if(colon && *(colon+1) == '\0')
167         {
168             *colon = '\0';
169             return _xcb_open_decnet(host, protocol, display);
170         }
171         else
172 #endif
173             if (protocol
174                 || strcmp("unix",host)) { /* follow the old unix: rule */
175
176                 /* display specifies TCP */
177                 unsigned short port = X_TCP_PORT + display;
178                 return _xcb_open_tcp(host, protocol, port);
179             }
180     }
181
182     filelen = strlen(base) + 1 + sizeof(display) * 3 + 1;
183     file = malloc(filelen);
184     if(file == NULL)
185         return -1;
186
187     /* display specifies Unix socket */
188 #ifdef HAVE_LAUNCHD
189     if(strncmp(base, "/tmp/launch", 11) == 0)
190         actual_filelen = snprintf(file, filelen, "%s:%d", base, display);
191     else
192 #endif
193         actual_filelen = snprintf(file, filelen, "%s%d", base, display);
194     if(actual_filelen < 0)
195     {
196         free(file);
197         return -1;
198     }
199     /* snprintf may truncate the file */
200     filelen = MIN(actual_filelen, filelen - 1);
201 #ifdef HAVE_ABSTRACT_SOCKETS
202     fd = _xcb_open_abstract(protocol, file, filelen);
203     if (fd >= 0 || (errno != ENOENT && errno != ECONNREFUSED))
204     {
205         free(file);
206         return fd;
207     }
208
209 #endif
210     fd = _xcb_open_unix(protocol, file);
211     free(file);
212
213     return fd;
214 }
215
216 static int _xcb_socket(int family, int type, int proto)
217 {
218     int fd;
219
220 #ifdef SOCK_CLOEXEC
221     fd = socket(family, type | SOCK_CLOEXEC, proto);
222     if (fd == -1 && errno == EINVAL)
223 #endif
224     {
225         fd = socket(family, type, proto);
226         if (fd >= 0)
227             fcntl(fd, F_SETFD, FD_CLOEXEC);
228     }
229     return fd;
230 }
231
232 #ifdef DNETCONN
233 static int _xcb_open_decnet(const char *host, const char *protocol, const unsigned short port)
234 {
235     int fd;
236     struct sockaddr_dn addr;
237     struct accessdata_dn accessdata;
238     struct nodeent *nodeaddr = getnodebyname(host);
239
240     if(!nodeaddr)
241         return -1;
242     if (protocol && strcmp("dnet",protocol))
243         return -1;
244     addr.sdn_family = AF_DECnet;
245
246     addr.sdn_add.a_len = nodeaddr->n_length;
247     memcpy(addr.sdn_add.a_addr, nodeaddr->n_addr, addr.sdn_add.a_len);
248
249     addr.sdn_objnamel = sprintf((char *)addr.sdn_objname, "X$X%d", port);
250     if(addr.sdn_objnamel < 0)
251         return -1;
252     addr.sdn_objnum = 0;
253
254     fd = _xcb_socket(PF_DECnet, SOCK_STREAM, 0);
255     if(fd == -1)
256         return -1;
257
258     memset(&accessdata, 0, sizeof(accessdata));
259     accessdata.acc_accl = sprintf((char*)accessdata.acc_acc, "%d", getuid());
260     if(accessdata.acc_accl < 0)
261         return -1;
262     setsockopt(fd, DNPROTO_NSP, SO_CONACCESS, &accessdata, sizeof(accessdata));
263
264     if(connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
265         close(fd);
266         return -1;
267     }
268     return fd;
269 }
270 #endif
271
272 static int _xcb_open_tcp(const char *host, char *protocol, const unsigned short port)
273 {
274     int fd = -1;
275     struct addrinfo hints;
276     char service[6]; /* "65535" with the trailing '\0' */
277     struct addrinfo *results, *addr;
278     char *bracket;
279
280     if (protocol && strcmp("tcp",protocol) && strcmp("inet",protocol)
281 #ifdef AF_INET6
282                  && strcmp("inet6",protocol)
283 #endif
284         )
285         return -1;
286         
287     if (*host == '\0')
288         host = "localhost";
289
290     memset(&hints, 0, sizeof(hints));
291 #ifdef AI_ADDRCONFIG
292     hints.ai_flags |= AI_ADDRCONFIG;
293 #endif
294 #ifdef AI_NUMERICSERV
295     hints.ai_flags |= AI_NUMERICSERV;
296 #endif
297     hints.ai_family = AF_UNSPEC;
298     hints.ai_socktype = SOCK_STREAM;
299
300 #ifdef AF_INET6
301     /* Allow IPv6 addresses enclosed in brackets. */
302     if(host[0] == '[' && (bracket = strrchr(host, ']')) && bracket[1] == '\0')
303     {
304         *bracket = '\0';
305         ++host;
306         hints.ai_flags |= AI_NUMERICHOST;
307         hints.ai_family = AF_INET6;
308     }
309 #endif
310
311     snprintf(service, sizeof(service), "%hu", port);
312     if(getaddrinfo(host, service, &hints, &results))
313         /* FIXME: use gai_strerror, and fill in error connection */
314         return -1;
315
316     for(addr = results; addr; addr = addr->ai_next)
317     {
318         fd = _xcb_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
319         if(fd >= 0) {
320             int on = 1;
321             setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
322             setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
323
324             if (connect(fd, addr->ai_addr, addr->ai_addrlen) >= 0)
325                 break;
326             close(fd);
327             fd = -1;
328         }
329     }
330     freeaddrinfo(results);
331     return fd;
332 }
333
334 static int _xcb_open_unix(char *protocol, const char *file)
335 {
336     int fd;
337     struct sockaddr_un addr;
338
339     if (protocol && strcmp("unix",protocol))
340         return -1;
341
342     strcpy(addr.sun_path, file);
343     addr.sun_family = AF_UNIX;
344 #ifdef HAVE_SOCKADDR_SUN_LEN
345     addr.sun_len = SUN_LEN(&addr);
346 #endif
347     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
348     if(fd == -1)
349         return -1;
350     if(connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
351         close(fd);
352         return -1;
353     }
354     return fd;
355 }
356
357 #ifdef HAVE_ABSTRACT_SOCKETS
358 static int _xcb_open_abstract(char *protocol, const char *file, size_t filelen)
359 {
360     int fd;
361     struct sockaddr_un addr = {0};
362     socklen_t namelen;
363
364     if (protocol && strcmp("unix",protocol))
365         return -1;
366
367     strcpy(addr.sun_path + 1, file);
368     addr.sun_family = AF_UNIX;
369     namelen = offsetof(struct sockaddr_un, sun_path) + 1 + filelen;
370 #ifdef HAVE_SOCKADDR_SUN_LEN
371     addr.sun_len = 1 + filelen;
372 #endif
373     fd = _xcb_socket(AF_UNIX, SOCK_STREAM, 0);
374     if (fd == -1)
375         return -1;
376     if (connect(fd, (struct sockaddr *) &addr, namelen) == -1) {
377         close(fd);
378         return -1;
379     }
380     return fd;
381 }
382 #endif
383
384 xcb_connection_t *xcb_connect(const char *displayname, int *screenp)
385 {
386     return xcb_connect_to_display_with_auth_info(displayname, NULL, screenp);
387 }
388
389 xcb_connection_t *xcb_connect_to_display_with_auth_info(const char *displayname, xcb_auth_info_t *auth, int *screenp)
390 {
391     int fd, display = 0;
392     char *host;
393     char *protocol;
394     xcb_auth_info_t ourauth;
395     xcb_connection_t *c;
396
397     int parsed = _xcb_parse_display(displayname, &host, &protocol, &display, screenp);
398     
399     if(!parsed)
400         return (xcb_connection_t *) &error_connection;
401     else
402         fd = _xcb_open(host, protocol, display);
403     free(host);
404
405     if(fd == -1)
406         return (xcb_connection_t *) &error_connection;
407
408     if(auth)
409         return xcb_connect_to_fd(fd, auth);
410
411     if(_xcb_get_auth_info(fd, &ourauth, display))
412     {
413         c = xcb_connect_to_fd(fd, &ourauth);
414         free(ourauth.name);
415         free(ourauth.data);
416     }
417     else
418         c = xcb_connect_to_fd(fd, 0);
419
420     return c;
421 }