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