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