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