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