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