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