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