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