Add configure option to enable or disable fd passing with sendmsg
[free-sw/xcb/libxcb] / src / xcb_conn.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 /* Connection management: the core of XCB. */
27
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31
32 #include <assert.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <unistd.h>
36 #include <stdlib.h>
37 #include <fcntl.h>
38 #include <errno.h>
39 #include <limits.h>
40
41 #include "xcb.h"
42 #include "xcbint.h"
43 #if USE_POLL
44 #include <poll.h>
45 #elif !defined _WIN32
46 #include <sys/select.h>
47 #endif
48
49 #ifdef _WIN32
50 #include "xcb_windefs.h"
51 #else
52 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #endif /* _WIN32 */
55
56 /* SHUT_RDWR is fairly recent and is not available on all platforms */
57 #if !defined(SHUT_RDWR)
58 #define SHUT_RDWR 2
59 #endif
60
61 typedef struct {
62     uint8_t  status;
63     uint8_t  pad0[5];
64     uint16_t length;
65 } xcb_setup_generic_t;
66
67 static const int xcb_con_error = XCB_CONN_ERROR;
68 static const int xcb_con_closed_mem_er = XCB_CONN_CLOSED_MEM_INSUFFICIENT;
69 static const int xcb_con_closed_parse_er = XCB_CONN_CLOSED_PARSE_ERR;
70 static const int xcb_con_closed_screen_er = XCB_CONN_CLOSED_INVALID_SCREEN;
71
72 static int set_fd_flags(const int fd)
73 {
74 /* Win32 doesn't have file descriptors and the fcntl function. This block sets the socket in non-blocking mode */
75
76 #ifdef _WIN32
77    u_long iMode = 1; /* non-zero puts it in non-blocking mode, 0 in blocking mode */   
78    int ret = 0;
79
80    ret = ioctlsocket(fd, FIONBIO, &iMode);
81    if(ret != 0) 
82        return 0;
83    return 1;
84 #else
85     int flags = fcntl(fd, F_GETFL, 0);
86     if(flags == -1)
87         return 0;
88     flags |= O_NONBLOCK;
89     if(fcntl(fd, F_SETFL, flags) == -1)
90         return 0;
91     if(fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
92         return 0;
93     return 1;
94 #endif /* _WIN32 */
95 }
96
97 static int write_setup(xcb_connection_t *c, xcb_auth_info_t *auth_info)
98 {
99     static const char pad[3];
100     xcb_setup_request_t out;
101     struct iovec parts[6];
102     int count = 0;
103     static const uint32_t endian = 0x01020304;
104     int ret;
105
106     memset(&out, 0, sizeof(out));
107
108     /* B = 0x42 = MSB first, l = 0x6c = LSB first */
109     if(htonl(endian) == endian)
110         out.byte_order = 0x42;
111     else
112         out.byte_order = 0x6c;
113     out.protocol_major_version = X_PROTOCOL;
114     out.protocol_minor_version = X_PROTOCOL_REVISION;
115     out.authorization_protocol_name_len = 0;
116     out.authorization_protocol_data_len = 0;
117     parts[count].iov_len = sizeof(xcb_setup_request_t);
118     parts[count++].iov_base = &out;
119     parts[count].iov_len = XCB_PAD(sizeof(xcb_setup_request_t));
120     parts[count++].iov_base = (char *) pad;
121
122     if(auth_info)
123     {
124         parts[count].iov_len = out.authorization_protocol_name_len = auth_info->namelen;
125         parts[count++].iov_base = auth_info->name;
126         parts[count].iov_len = XCB_PAD(out.authorization_protocol_name_len);
127         parts[count++].iov_base = (char *) pad;
128         parts[count].iov_len = out.authorization_protocol_data_len = auth_info->datalen;
129         parts[count++].iov_base = auth_info->data;
130         parts[count].iov_len = XCB_PAD(out.authorization_protocol_data_len);
131         parts[count++].iov_base = (char *) pad;
132     }
133     assert(count <= (int) (sizeof(parts) / sizeof(*parts)));
134
135     pthread_mutex_lock(&c->iolock);
136     ret = _xcb_out_send(c, parts, count);
137     pthread_mutex_unlock(&c->iolock);
138     return ret;
139 }
140
141 static int read_setup(xcb_connection_t *c)
142 {
143     /* Read the server response */
144     c->setup = malloc(sizeof(xcb_setup_generic_t));
145     if(!c->setup)
146         return 0;
147
148     if(_xcb_in_read_block(c, c->setup, sizeof(xcb_setup_generic_t)) != sizeof(xcb_setup_generic_t))
149         return 0;
150
151     {
152         void *tmp = realloc(c->setup, c->setup->length * 4 + sizeof(xcb_setup_generic_t));
153         if(!tmp)
154             return 0;
155         c->setup = tmp;
156     }
157
158     if(_xcb_in_read_block(c, (char *) c->setup + sizeof(xcb_setup_generic_t), c->setup->length * 4) <= 0)
159         return 0;
160
161     /* 0 = failed, 2 = authenticate, 1 = success */
162     switch(c->setup->status)
163     {
164     case 0: /* failed */
165         {
166             xcb_setup_failed_t *setup = (xcb_setup_failed_t *) c->setup;
167             write(STDERR_FILENO, xcb_setup_failed_reason(setup), xcb_setup_failed_reason_length(setup));
168             return 0;
169         }
170
171     case 2: /* authenticate */
172         {
173             xcb_setup_authenticate_t *setup = (xcb_setup_authenticate_t *) c->setup;
174             write(STDERR_FILENO, xcb_setup_authenticate_reason(setup), xcb_setup_authenticate_reason_length(setup));
175             return 0;
176         }
177     }
178
179     return 1;
180 }
181
182 /* precondition: there must be something for us to write. */
183 static int write_vec(xcb_connection_t *c, struct iovec **vector, int *count)
184 {
185     int n;
186     assert(!c->out.queue_len);
187
188 #ifdef _WIN32
189     int i = 0;
190     int ret = 0,err = 0;
191     struct iovec *vec;
192     n = 0;
193
194     /* Could use the WSASend win32 function for scatter/gather i/o but setting up the WSABUF struct from
195        an iovec would require more work and I'm not sure of the benefit....works for now */
196     vec = *vector;
197     while(i < *count)
198     {            
199          ret = send(c->fd,vec->iov_base,vec->iov_len,0);         
200          if(ret == SOCKET_ERROR)
201          {
202              err  = WSAGetLastError();
203              if(err == WSAEWOULDBLOCK)
204              {
205                  return 1;
206              }
207          }
208          n += ret;
209          *vec++;
210          i++;
211     }
212 #else
213     n = *count;
214     if (n > IOV_MAX)
215         n = IOV_MAX;
216
217 #if HAVE_SENDMSG
218     if (c->out.out_fd.nfd) {
219         char cmsgbuf[CMSG_SPACE(sizeof(int) * XCB_MAX_PASS_FD)];
220         struct msghdr msg = {
221             .msg_name = NULL,
222             .msg_namelen = 0,
223             .msg_iov = *vector,
224             .msg_iovlen = n,
225             .msg_control = cmsgbuf,
226             .msg_controllen = CMSG_LEN(c->out.out_fd.nfd * sizeof (int)),
227         };
228         int i;
229         struct cmsghdr *hdr = CMSG_FIRSTHDR(&msg);
230
231         hdr->cmsg_len = msg.msg_controllen;
232         hdr->cmsg_level = SOL_SOCKET;
233         hdr->cmsg_type = SCM_RIGHTS;
234         memcpy(CMSG_DATA(hdr), c->out.out_fd.fd, c->out.out_fd.nfd * sizeof (int));
235
236         n = sendmsg(c->fd, &msg, 0);
237         if(n < 0 && errno == EAGAIN)
238             return 1;
239         for (i = 0; i < c->out.out_fd.nfd; i++)
240             close(c->out.out_fd.fd[i]);
241         c->out.out_fd.nfd = 0;
242     } else
243 #endif
244     {
245         n = writev(c->fd, *vector, n);
246         if(n < 0 && errno == EAGAIN)
247             return 1;
248     }
249
250 #endif /* _WIN32 */    
251
252     if(n <= 0)
253     {
254         _xcb_conn_shutdown(c, XCB_CONN_ERROR);
255         return 0;
256     }
257
258     for(; *count; --*count, ++*vector)
259     {
260         int cur = (*vector)->iov_len;
261         if(cur > n)
262             cur = n;
263         (*vector)->iov_len -= cur;
264         (*vector)->iov_base = (char *) (*vector)->iov_base + cur;
265         n -= cur;
266         if((*vector)->iov_len)
267             break;
268     }
269     if(!*count)
270         *vector = 0;
271     assert(n == 0);
272     return 1;
273 }
274
275 /* Public interface */
276
277 const xcb_setup_t *xcb_get_setup(xcb_connection_t *c)
278 {
279     if(c->has_error)
280         return 0;
281     /* doesn't need locking because it's never written to. */
282     return c->setup;
283 }
284
285 int xcb_get_file_descriptor(xcb_connection_t *c)
286 {
287     if(c->has_error)
288         return -1;
289     /* doesn't need locking because it's never written to. */
290     return c->fd;
291 }
292
293 int xcb_connection_has_error(xcb_connection_t *c)
294 {
295     /* doesn't need locking because it's read and written atomically. */
296     return c->has_error;
297 }
298
299 xcb_connection_t *xcb_connect_to_fd(int fd, xcb_auth_info_t *auth_info)
300 {
301     xcb_connection_t* c;
302
303 #ifndef _WIN32
304 #ifndef USE_POLL
305     if(fd >= FD_SETSIZE) /* would overflow in FD_SET */
306     {
307         close(fd);
308         return _xcb_conn_ret_error(XCB_CONN_ERROR);
309     }
310 #endif
311 #endif /* !_WIN32*/
312
313     c = calloc(1, sizeof(xcb_connection_t));
314     if(!c) {
315         close(fd);
316         return _xcb_conn_ret_error(XCB_CONN_CLOSED_MEM_INSUFFICIENT) ;
317     }
318
319     c->fd = fd;
320
321     if(!(
322         set_fd_flags(fd) &&
323         pthread_mutex_init(&c->iolock, 0) == 0 &&
324         _xcb_in_init(&c->in) &&
325         _xcb_out_init(&c->out) &&
326         write_setup(c, auth_info) &&
327         read_setup(c) &&
328         _xcb_ext_init(c) &&
329         _xcb_xid_init(c)
330         ))
331     {
332         xcb_disconnect(c);
333         return _xcb_conn_ret_error(XCB_CONN_ERROR);
334     }
335
336     return c;
337 }
338
339 void xcb_disconnect(xcb_connection_t *c)
340 {
341     if(c->has_error)
342         return;
343
344     free(c->setup);
345
346     /* disallow further sends and receives */
347     shutdown(c->fd, SHUT_RDWR);
348     close(c->fd);
349
350     pthread_mutex_destroy(&c->iolock);
351     _xcb_in_destroy(&c->in);
352     _xcb_out_destroy(&c->out);
353
354     _xcb_ext_destroy(c);
355     _xcb_xid_destroy(c);
356
357     free(c);
358
359 #ifdef _WIN32
360     WSACleanup();
361 #endif
362 }
363
364 /* Private interface */
365
366 void _xcb_conn_shutdown(xcb_connection_t *c, int err)
367 {
368     c->has_error = err;
369 }
370
371 /* Return connection error state.
372  * To make thread-safe, I need a seperate static
373  * variable for every possible error.
374  */
375 xcb_connection_t *_xcb_conn_ret_error(int err)
376 {
377
378     switch(err)
379     {
380         case XCB_CONN_CLOSED_MEM_INSUFFICIENT:
381         {
382             return (xcb_connection_t *) &xcb_con_closed_mem_er;
383         }
384         case XCB_CONN_CLOSED_PARSE_ERR:
385         {
386             return (xcb_connection_t *) &xcb_con_closed_parse_er;
387         }
388         case XCB_CONN_CLOSED_INVALID_SCREEN:
389         {
390             return (xcb_connection_t *) &xcb_con_closed_screen_er;
391         }
392         case XCB_CONN_ERROR:
393         default:
394         {
395             return (xcb_connection_t *) &xcb_con_error;
396         }
397     }
398 }
399
400 int _xcb_conn_wait(xcb_connection_t *c, pthread_cond_t *cond, struct iovec **vector, int *count)
401 {
402     int ret;
403 #if USE_POLL
404     struct pollfd fd;
405 #else
406     fd_set rfds, wfds;
407 #endif
408
409     /* If the thing I should be doing is already being done, wait for it. */
410     if(count ? c->out.writing : c->in.reading)
411     {
412         pthread_cond_wait(cond, &c->iolock);
413         return 1;
414     }
415
416 #if USE_POLL
417     memset(&fd, 0, sizeof(fd));
418     fd.fd = c->fd;
419     fd.events = POLLIN;
420 #else
421     FD_ZERO(&rfds);
422     FD_SET(c->fd, &rfds);
423 #endif
424     ++c->in.reading;
425
426 #if USE_POLL
427     if(count)
428     {
429         fd.events |= POLLOUT;
430         ++c->out.writing;
431     }
432 #else
433     FD_ZERO(&wfds);
434     if(count)
435     {
436         FD_SET(c->fd, &wfds);
437         ++c->out.writing;
438     }
439 #endif
440
441     pthread_mutex_unlock(&c->iolock);
442     do {
443 #if USE_POLL
444         ret = poll(&fd, 1, -1);
445         /* If poll() returns an event we didn't expect, such as POLLNVAL, treat
446          * it as if it failed. */
447         if(ret >= 0 && (fd.revents & ~fd.events))
448         {
449             ret = -1;
450             break;
451         }
452 #else
453         ret = select(c->fd + 1, &rfds, &wfds, 0, 0);
454 #endif
455     } while (ret == -1 && errno == EINTR);
456     if(ret < 0)
457     {
458         _xcb_conn_shutdown(c, XCB_CONN_ERROR);
459         ret = 0;
460     }
461     pthread_mutex_lock(&c->iolock);
462
463     if(ret)
464     {
465         /* The code allows two threads to call select()/poll() at the same time.
466          * First thread just wants to read, a second thread wants to write, too.
467          * We have to make sure that we don't steal the reading thread's reply
468          * and let it get stuck in select()/poll().
469          * So a thread may read if either:
470          * - There is no other thread that wants to read (the above situation
471          *   did not occur).
472          * - It is the reading thread (above situation occurred).
473          */
474         int may_read = c->in.reading == 1 || !count;
475 #if USE_POLL
476         if(may_read && (fd.revents & POLLIN) != 0)
477 #else
478         if(may_read && FD_ISSET(c->fd, &rfds))
479 #endif
480             ret = ret && _xcb_in_read(c);
481
482 #if USE_POLL
483         if((fd.revents & POLLOUT) != 0)
484 #else
485         if(FD_ISSET(c->fd, &wfds))
486 #endif
487             ret = ret && write_vec(c, vector, count);
488     }
489
490     if(count)
491         --c->out.writing;
492     --c->in.reading;
493
494     return ret;
495 }