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