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