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