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