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