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