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