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