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