server: Hold a pointer to the queue from the async operations.
[wine] / server / sock.c
1 /*
2  * Server-side socket management
3  *
4  * Copyright (C) 1999 Marcus Meissner, Ove Kåven
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * FIXME: we use read|write access in all cases. Shouldn't we depend that
21  * on the access of the current handle?
22  */
23
24 #include "config.h"
25
26 #include <assert.h>
27 #include <fcntl.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32 #include <errno.h>
33 #ifdef HAVE_SYS_ERRNO_H
34 # include <sys/errno.h>
35 #endif
36 #include <sys/time.h>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_SOCKET_H
39 # include <sys/socket.h>
40 #endif
41 #ifdef HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
43 #endif
44 #ifdef HAVE_SYS_FILIO_H
45 # include <sys/filio.h>
46 #endif
47 #include <time.h>
48 #include <unistd.h>
49
50 #include "ntstatus.h"
51 #define WIN32_NO_STATUS
52 #include "windef.h"
53 #include "winternl.h"
54
55 #include "process.h"
56 #include "file.h"
57 #include "handle.h"
58 #include "thread.h"
59 #include "request.h"
60 #include "user.h"
61
62 /* To avoid conflicts with the Unix socket headers. Plus we only need a few
63  * macros anyway.
64  */
65 #define USE_WS_PREFIX
66 #include "winsock2.h"
67
68 struct sock
69 {
70     struct object       obj;         /* object header */
71     struct fd          *fd;          /* socket file descriptor */
72     unsigned int        state;       /* status bits */
73     unsigned int        mask;        /* event mask */
74     unsigned int        hmask;       /* held (blocked) events */
75     unsigned int        pmask;       /* pending events */
76     unsigned int        flags;       /* socket flags */
77     int                 polling;     /* is socket being polled? */
78     unsigned short      type;        /* socket type */
79     unsigned short      family;      /* socket family */
80     struct event       *event;       /* event object */
81     user_handle_t       window;      /* window to send the message to */
82     unsigned int        message;     /* message to send */
83     obj_handle_t        wparam;      /* message wparam (socket handle) */
84     int                 errors[FD_MAX_EVENTS]; /* event errors */
85     struct sock        *deferred;    /* socket that waits for a deferred accept */
86     struct async_queue *read_q;      /* queue for asynchronous reads */
87     struct async_queue *write_q;     /* queue for asynchronous writes */
88 };
89
90 static void sock_dump( struct object *obj, int verbose );
91 static int sock_signaled( struct object *obj, struct thread *thread );
92 static struct fd *sock_get_fd( struct object *obj );
93 static unsigned int sock_map_access( struct object *obj, unsigned int access );
94 static void sock_destroy( struct object *obj );
95
96 static int sock_get_poll_events( struct fd *fd );
97 static void sock_poll_event( struct fd *fd, int event );
98 static enum server_fd_type sock_get_info( struct fd *fd, int *flags );
99 static void sock_queue_async( struct fd *fd, const async_data_t *data, int type, int count );
100 static void sock_cancel_async( struct fd *fd );
101
102 static int sock_get_error( int err );
103 static void sock_set_error(void);
104
105 static const struct object_ops sock_ops =
106 {
107     sizeof(struct sock),          /* size */
108     sock_dump,                    /* dump */
109     add_queue,                    /* add_queue */
110     remove_queue,                 /* remove_queue */
111     sock_signaled,                /* signaled */
112     no_satisfied,                 /* satisfied */
113     no_signal,                    /* signal */
114     sock_get_fd,                  /* get_fd */
115     sock_map_access,              /* map_access */
116     no_lookup_name,               /* lookup_name */
117     no_open_file,                 /* open_file */
118     fd_close_handle,              /* close_handle */
119     sock_destroy                  /* destroy */
120 };
121
122 static const struct fd_ops sock_fd_ops =
123 {
124     sock_get_poll_events,         /* get_poll_events */
125     sock_poll_event,              /* poll_event */
126     no_flush,                     /* flush */
127     sock_get_info,                /* get_file_info */
128     sock_queue_async,             /* queue_async */
129     sock_cancel_async             /* cancel_async */
130 };
131
132
133 /* Permutation of 0..FD_MAX_EVENTS - 1 representing the order in which
134  * we post messages if there are multiple events.  Used to send
135  * messages.  The problem is if there is both a FD_CONNECT event and,
136  * say, an FD_READ event available on the same socket, we want to
137  * notify the app of the connect event first.  Otherwise it may
138  * discard the read event because it thinks it hasn't connected yet.
139  */
140 static const int event_bitorder[FD_MAX_EVENTS] =
141 {
142     FD_CONNECT_BIT,
143     FD_ACCEPT_BIT,
144     FD_OOB_BIT,
145     FD_WRITE_BIT,
146     FD_READ_BIT,
147     FD_CLOSE_BIT,
148     6, 7, 8, 9  /* leftovers */
149 };
150
151 /* Flags that make sense only for SOCK_STREAM sockets */
152 #define STREAM_FLAG_MASK ((unsigned int) (FD_CONNECT | FD_ACCEPT | FD_WINE_LISTENING | FD_WINE_CONNECTED))
153
154 typedef enum {
155     SOCK_SHUTDOWN_ERROR = -1,
156     SOCK_SHUTDOWN_EOF = 0,
157     SOCK_SHUTDOWN_POLLHUP = 1
158 } sock_shutdown_t;
159
160 static sock_shutdown_t sock_shutdown_type = SOCK_SHUTDOWN_ERROR;
161
162 static sock_shutdown_t sock_check_pollhup(void)
163 {
164     sock_shutdown_t ret = SOCK_SHUTDOWN_ERROR;
165     int fd[2], n;
166     struct pollfd pfd;
167     char dummy;
168
169     if ( socketpair( AF_UNIX, SOCK_STREAM, 0, fd ) ) goto out;
170     if ( shutdown( fd[0], 1 ) ) goto out;
171
172     pfd.fd = fd[1];
173     pfd.events = POLLIN;
174     pfd.revents = 0;
175
176     n = poll( &pfd, 1, 0 );
177     if ( n != 1 ) goto out; /* error or timeout */
178     if ( pfd.revents & POLLHUP )
179         ret = SOCK_SHUTDOWN_POLLHUP;
180     else if ( pfd.revents & POLLIN &&
181               read( fd[1], &dummy, 1 ) == 0 )
182         ret = SOCK_SHUTDOWN_EOF;
183
184 out:
185     close( fd[0] );
186     close( fd[1] );
187     return ret;
188 }
189
190 void sock_init(void)
191 {
192     sock_shutdown_type = sock_check_pollhup();
193
194     switch ( sock_shutdown_type )
195     {
196     case SOCK_SHUTDOWN_EOF:
197         if (debug_level) fprintf( stderr, "sock_init: shutdown() causes EOF\n" );
198         break;
199     case SOCK_SHUTDOWN_POLLHUP:
200         if (debug_level) fprintf( stderr, "sock_init: shutdown() causes POLLHUP\n" );
201         break;
202     default:
203         fprintf( stderr, "sock_init: ERROR in sock_check_pollhup()\n" );
204         sock_shutdown_type = SOCK_SHUTDOWN_EOF;
205     }
206 }
207
208 static int sock_reselect( struct sock *sock )
209 {
210     int ev = sock_get_poll_events( sock->fd );
211
212     if (debug_level)
213         fprintf(stderr,"sock_reselect(%p): new mask %x\n", sock, ev);
214
215     if (!sock->polling)  /* FIXME: should find a better way to do this */
216     {
217         /* previously unconnected socket, is this reselect supposed to connect it? */
218         if (!(sock->state & ~FD_WINE_NONBLOCKING)) return 0;
219         /* ok, it is, attach it to the wineserver's main poll loop */
220         sock->polling = 1;
221     }
222     /* update condition mask */
223     set_fd_events( sock->fd, ev );
224     return ev;
225 }
226
227 /* After POLLHUP is received, the socket will no longer be in the main select loop.
228    This function is used to signal pending events nevertheless */
229 static void sock_try_event( struct sock *sock, int event )
230 {
231     event = check_fd_events( sock->fd, event );
232     if (event)
233     {
234         if ( debug_level ) fprintf( stderr, "sock_try_event: %x\n", event );
235         sock_poll_event( sock->fd, event );
236     }
237 }
238
239 /* wake anybody waiting on the socket event or send the associated message */
240 static void sock_wake_up( struct sock *sock, int pollev )
241 {
242     unsigned int events = sock->pmask & sock->mask;
243     int i;
244     int async_active = 0;
245
246     if ( sock->flags & WSA_FLAG_OVERLAPPED )
247     {
248         if ( pollev & (POLLIN|POLLPRI) && async_waiting( sock->read_q ))
249         {
250             if (debug_level) fprintf( stderr, "activating read queue for socket %p\n", sock );
251             async_wake_up( sock->read_q, STATUS_ALERTED );
252             async_active = 1;
253         }
254         if ( pollev & POLLOUT && async_waiting( sock->write_q ))
255         {
256             if (debug_level) fprintf( stderr, "activating write queue for socket %p\n", sock );
257             async_wake_up( sock->write_q, STATUS_ALERTED );
258             async_active = 1;
259         }
260     }
261
262     /* Do not signal events if there are still pending asynchronous IO requests */
263     /* We need this to delay FD_CLOSE events until all pending overlapped requests are processed */
264     if ( !events || async_active ) return;
265
266     if (sock->event)
267     {
268         if (debug_level) fprintf(stderr, "signalling events %x ptr %p\n", events, sock->event );
269         set_event( sock->event );
270     }
271     if (sock->window)
272     {
273         if (debug_level) fprintf(stderr, "signalling events %x win %p\n", events, sock->window );
274         for (i = 0; i < FD_MAX_EVENTS; i++)
275         {
276             int event = event_bitorder[i];
277             if (sock->pmask & (1 << event))
278             {
279                 unsigned int lparam = (1 << event) | (sock->errors[event] << 16);
280                 post_message( sock->window, sock->message, (unsigned long)sock->wparam, lparam );
281             }
282         }
283         sock->pmask = 0;
284         sock_reselect( sock );
285     }
286 }
287
288 static inline int sock_error( struct fd *fd )
289 {
290     unsigned int optval = 0, optlen;
291
292     optlen = sizeof(optval);
293     getsockopt( get_unix_fd(fd), SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
294     return optval ? sock_get_error(optval) : 0;
295 }
296
297 static void sock_poll_event( struct fd *fd, int event )
298 {
299     struct sock *sock = get_fd_user( fd );
300     int hangup_seen = 0;
301
302     assert( sock->obj.ops == &sock_ops );
303     if (debug_level)
304         fprintf(stderr, "socket %p select event: %x\n", sock, event);
305     if (sock->state & FD_CONNECT)
306     {
307         /* connecting */
308         if (event & POLLOUT)
309         {
310             /* we got connected */
311             sock->state |= FD_WINE_CONNECTED|FD_READ|FD_WRITE;
312             sock->state &= ~FD_CONNECT;
313             sock->pmask |= FD_CONNECT;
314             sock->errors[FD_CONNECT_BIT] = 0;
315             if (debug_level)
316                 fprintf(stderr, "socket %p connection success\n", sock);
317         }
318         else if (event & (POLLERR|POLLHUP))
319         {
320             /* we didn't get connected? */
321             sock->state &= ~FD_CONNECT;
322             sock->pmask |= FD_CONNECT;
323             sock->errors[FD_CONNECT_BIT] = sock_error( fd );
324             if (debug_level)
325                 fprintf(stderr, "socket %p connection failure\n", sock);
326         }
327     }
328     else if (sock->state & FD_WINE_LISTENING)
329     {
330         /* listening */
331         if (event & POLLIN)
332         {
333             /* incoming connection */
334             sock->pmask |= FD_ACCEPT;
335             sock->errors[FD_ACCEPT_BIT] = 0;
336             sock->hmask |= FD_ACCEPT;
337         }
338         else if (event & (POLLERR|POLLHUP))
339         {
340             /* failed incoming connection? */
341             sock->pmask |= FD_ACCEPT;
342             sock->errors[FD_ACCEPT_BIT] = sock_error( fd );
343             sock->hmask |= FD_ACCEPT;
344         }
345     }
346     else
347     {
348         /* normal data flow */
349         if ( sock->type == SOCK_STREAM && ( event & POLLIN ) )
350         {
351             char dummy;
352             int nr;
353
354             /* Linux 2.4 doesn't report POLLHUP if only one side of the socket
355              * has been closed, so we need to check for it explicitly here */
356             nr  = recv( get_unix_fd( fd ), &dummy, 1, MSG_PEEK );
357             if ( nr > 0 )
358             {
359                 /* incoming data */
360                 sock->pmask |= FD_READ;
361                 sock->hmask |= (FD_READ|FD_CLOSE);
362                 sock->errors[FD_READ_BIT] = 0;
363                 if (debug_level)
364                     fprintf(stderr, "socket %p is readable\n", sock );
365             }
366             else if ( nr == 0 )
367                 hangup_seen = 1;
368             else
369             {
370                 /* EAGAIN can happen if an async recv() falls between the server's poll()
371                    call and the invocation of this routine */
372                 if ( errno == EAGAIN )
373                     event &= ~POLLIN;
374                 else
375                 {
376                     if ( debug_level )
377                         fprintf( stderr, "recv error on socket %p: %d\n", sock, errno );
378                     event = POLLERR;
379                 }
380             }
381
382         }
383         else if ( sock_shutdown_type == SOCK_SHUTDOWN_POLLHUP && (event & POLLHUP) )
384         {
385             hangup_seen = 1;
386         }
387         else if ( event & POLLIN ) /* POLLIN for non-stream socket */
388         {
389             sock->pmask |= FD_READ;
390             sock->hmask |= (FD_READ|FD_CLOSE);
391             sock->errors[FD_READ_BIT] = 0;
392             if (debug_level)
393                 fprintf(stderr, "socket %p is readable\n", sock );
394
395         }
396
397         if (event & POLLOUT)
398         {
399             sock->pmask |= FD_WRITE;
400             sock->hmask |= FD_WRITE;
401             sock->errors[FD_WRITE_BIT] = 0;
402             if (debug_level)
403                 fprintf(stderr, "socket %p is writable\n", sock);
404         }
405         if (event & POLLPRI)
406         {
407             sock->pmask |= FD_OOB;
408             sock->hmask |= FD_OOB;
409             sock->errors[FD_OOB_BIT] = 0;
410             if (debug_level)
411                 fprintf(stderr, "socket %p got OOB data\n", sock);
412         }
413         /* According to WS2 specs, FD_CLOSE is only delivered when there is
414            no more data to be read (i.e. hangup_seen = 1) */
415         else if ( hangup_seen && (sock->state & (FD_READ|FD_WRITE) ))
416         {
417             sock->errors[FD_CLOSE_BIT] = sock_error( fd );
418             if ( (event & POLLERR) || ( sock_shutdown_type == SOCK_SHUTDOWN_EOF && (event & POLLHUP) ))
419                 sock->state &= ~FD_WRITE;
420             sock->pmask |= FD_CLOSE;
421             sock->hmask |= FD_CLOSE;
422             if (debug_level)
423                 fprintf(stderr, "socket %p aborted by error %d, event: %x - removing from select loop\n",
424                         sock, sock->errors[FD_CLOSE_BIT], event);
425         }
426     }
427
428     if ( sock->pmask & FD_CLOSE || event & (POLLERR|POLLHUP) )
429     {
430         if ( debug_level )
431             fprintf( stderr, "removing socket %p from select loop\n", sock );
432         set_fd_events( sock->fd, -1 );
433     }
434     else
435         sock_reselect( sock );
436
437     /* wake up anyone waiting for whatever just happened */
438     if ( sock->pmask & sock->mask || sock->flags & WSA_FLAG_OVERLAPPED ) sock_wake_up( sock, event );
439
440     /* if anyone is stupid enough to wait on the socket object itself,
441      * maybe we should wake them up too, just in case? */
442     wake_up( &sock->obj, 0 );
443 }
444
445 static void sock_dump( struct object *obj, int verbose )
446 {
447     struct sock *sock = (struct sock *)obj;
448     assert( obj->ops == &sock_ops );
449     printf( "Socket fd=%p, state=%x, mask=%x, pending=%x, held=%x\n",
450             sock->fd, sock->state,
451             sock->mask, sock->pmask, sock->hmask );
452 }
453
454 static int sock_signaled( struct object *obj, struct thread *thread )
455 {
456     struct sock *sock = (struct sock *)obj;
457     assert( obj->ops == &sock_ops );
458
459     return check_fd_events( sock->fd, sock_get_poll_events( sock->fd ) ) != 0;
460 }
461
462 static unsigned int sock_map_access( struct object *obj, unsigned int access )
463 {
464     if (access & GENERIC_READ)    access |= FILE_GENERIC_READ;
465     if (access & GENERIC_WRITE)   access |= FILE_GENERIC_WRITE;
466     if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
467     if (access & GENERIC_ALL)     access |= FILE_ALL_ACCESS;
468     return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
469 }
470
471 static int sock_get_poll_events( struct fd *fd )
472 {
473     struct sock *sock = get_fd_user( fd );
474     unsigned int mask = sock->mask & sock->state & ~sock->hmask;
475     int ev = 0;
476
477     assert( sock->obj.ops == &sock_ops );
478
479     if (sock->state & FD_CONNECT)
480         /* connecting, wait for writable */
481         return POLLOUT;
482     if (sock->state & FD_WINE_LISTENING)
483         /* listening, wait for readable */
484         return (sock->hmask & FD_ACCEPT) ? 0 : POLLIN;
485
486     if (mask & (FD_READ) || (sock->flags & WSA_FLAG_OVERLAPPED && async_waiting( sock->read_q )))
487         ev |= POLLIN | POLLPRI;
488     if (mask & FD_WRITE || (sock->flags & WSA_FLAG_OVERLAPPED && async_waiting( sock->write_q )))
489         ev |= POLLOUT;
490     /* We use POLLIN with 0 bytes recv() as FD_CLOSE indication for stream sockets. */
491     if ( sock->type == SOCK_STREAM && ( sock->mask & ~sock->hmask & FD_CLOSE) )
492         ev |= POLLIN;
493
494     return ev;
495 }
496
497 static enum server_fd_type sock_get_info( struct fd *fd, int *flags )
498 {
499     struct sock *sock = get_fd_user( fd );
500     assert( sock->obj.ops == &sock_ops );
501
502     *flags = FD_FLAG_AVAILABLE;
503     if (sock->flags & WSA_FLAG_OVERLAPPED) *flags |= FD_FLAG_OVERLAPPED;
504     if ( sock->type != SOCK_STREAM || sock->state & FD_WINE_CONNECTED )
505     {
506         if ( !(sock->state & FD_READ  ) ) *flags |= FD_FLAG_RECV_SHUTDOWN;
507         if ( !(sock->state & FD_WRITE ) ) *flags |= FD_FLAG_SEND_SHUTDOWN;
508     }
509     return FD_TYPE_SOCKET;
510 }
511
512 static void sock_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
513 {
514     struct sock *sock = get_fd_user( fd );
515     struct async_queue *queue;
516     int pollev;
517
518     assert( sock->obj.ops == &sock_ops );
519
520     if ( !(sock->flags & WSA_FLAG_OVERLAPPED) )
521     {
522         set_error( STATUS_INVALID_HANDLE );
523         return;
524     }
525
526     switch (type)
527     {
528     case ASYNC_TYPE_READ:
529         if (!sock->read_q && !(sock->read_q = create_async_queue( sock->fd ))) return;
530         queue = sock->read_q;
531         sock->hmask &= ~FD_CLOSE;
532         break;
533     case ASYNC_TYPE_WRITE:
534         if (!sock->write_q && !(sock->write_q = create_async_queue( sock->fd ))) return;
535         queue = sock->write_q;
536         break;
537     default:
538         set_error( STATUS_INVALID_PARAMETER );
539         return;
540     }
541
542     if ( ( !( sock->state & FD_READ ) && type == ASYNC_TYPE_READ  ) ||
543          ( !( sock->state & FD_WRITE ) && type == ASYNC_TYPE_WRITE ) )
544     {
545         set_error( STATUS_PIPE_DISCONNECTED );
546     }
547     else
548     {
549         struct async *async;
550         if (!(async = create_async( current, queue, data ))) return;
551         release_object( async );
552         set_error( STATUS_PENDING );
553     }
554
555     pollev = sock_reselect( sock );
556     if ( pollev ) sock_try_event( sock, pollev );
557 }
558
559 static void sock_cancel_async( struct fd *fd )
560 {
561     struct sock *sock = get_fd_user( fd );
562     assert( sock->obj.ops == &sock_ops );
563
564     async_wake_up( sock->read_q, STATUS_CANCELLED );
565     async_wake_up( sock->write_q, STATUS_CANCELLED );
566 }
567
568 static struct fd *sock_get_fd( struct object *obj )
569 {
570     struct sock *sock = (struct sock *)obj;
571     return (struct fd *)grab_object( sock->fd );
572 }
573
574 static void sock_destroy( struct object *obj )
575 {
576     struct sock *sock = (struct sock *)obj;
577     assert( obj->ops == &sock_ops );
578
579     /* FIXME: special socket shutdown stuff? */
580
581     if ( sock->deferred )
582         release_object( sock->deferred );
583
584     free_async_queue( sock->read_q );
585     free_async_queue( sock->write_q );
586     if (sock->event) release_object( sock->event );
587     if (sock->fd)
588     {
589         /* shut the socket down to force pending poll() calls in the client to return */
590         shutdown( get_unix_fd(sock->fd), SHUT_RDWR );
591         release_object( sock->fd );
592     }
593 }
594
595 /* create a new and unconnected socket */
596 static struct object *create_socket( int family, int type, int protocol, unsigned int flags )
597 {
598     struct sock *sock;
599     int sockfd;
600
601     sockfd = socket( family, type, protocol );
602     if (debug_level)
603         fprintf(stderr,"socket(%d,%d,%d)=%d\n",family,type,protocol,sockfd);
604     if (sockfd == -1)
605     {
606         sock_set_error();
607         return NULL;
608     }
609     fcntl(sockfd, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
610     if (!(sock = alloc_object( &sock_ops )))
611     {
612         close( sockfd );
613         return NULL;
614     }
615     sock->state = (type != SOCK_STREAM) ? (FD_READ|FD_WRITE) : 0;
616     sock->mask    = 0;
617     sock->hmask   = 0;
618     sock->pmask   = 0;
619     sock->polling = 0;
620     sock->flags   = flags;
621     sock->type    = type;
622     sock->family  = family;
623     sock->event   = NULL;
624     sock->window  = 0;
625     sock->message = 0;
626     sock->wparam  = 0;
627     sock->deferred = NULL;
628     sock->read_q  = NULL;
629     sock->write_q = NULL;
630     if (!(sock->fd = create_anonymous_fd( &sock_fd_ops, sockfd, &sock->obj )))
631     {
632         release_object( sock );
633         return NULL;
634     }
635     sock_reselect( sock );
636     clear_error();
637     return &sock->obj;
638 }
639
640 /* accept a socket (creates a new fd) */
641 static struct sock *accept_socket( obj_handle_t handle )
642 {
643     struct sock *acceptsock;
644     struct sock *sock;
645     int acceptfd;
646     struct sockaddr     saddr;
647
648     sock = (struct sock *)get_handle_obj( current->process, handle, FILE_READ_DATA, &sock_ops );
649     if (!sock)
650         return NULL;
651
652     if ( sock->deferred )
653     {
654         acceptsock = sock->deferred;
655         sock->deferred = NULL;
656     }
657     else
658     {
659
660         /* Try to accept(2). We can't be safe that this an already connected socket
661          * or that accept() is allowed on it. In those cases we will get -1/errno
662          * return.
663          */
664         unsigned int slen = sizeof(saddr);
665         acceptfd = accept( get_unix_fd(sock->fd), &saddr, &slen);
666         if (acceptfd==-1)
667         {
668             sock_set_error();
669             release_object( sock );
670             return NULL;
671         }
672         if (!(acceptsock = alloc_object( &sock_ops )))
673         {
674             close( acceptfd );
675             release_object( sock );
676             return NULL;
677         }
678
679         /* newly created socket gets the same properties of the listening socket */
680         fcntl(acceptfd, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
681         acceptsock->state  = FD_WINE_CONNECTED|FD_READ|FD_WRITE;
682         if (sock->state & FD_WINE_NONBLOCKING)
683             acceptsock->state |= FD_WINE_NONBLOCKING;
684         acceptsock->mask    = sock->mask;
685         acceptsock->hmask   = 0;
686         acceptsock->pmask   = 0;
687         acceptsock->polling = 0;
688         acceptsock->type    = sock->type;
689         acceptsock->family  = sock->family;
690         acceptsock->event   = NULL;
691         acceptsock->window  = sock->window;
692         acceptsock->message = sock->message;
693         acceptsock->wparam  = 0;
694         if (sock->event) acceptsock->event = (struct event *)grab_object( sock->event );
695         acceptsock->flags = sock->flags;
696         acceptsock->deferred = NULL;
697         acceptsock->read_q  = NULL;
698         acceptsock->write_q = NULL;
699         if (!(acceptsock->fd = create_anonymous_fd( &sock_fd_ops, acceptfd, &acceptsock->obj )))
700         {
701             release_object( acceptsock );
702             release_object( sock );
703             return NULL;
704         }
705     }
706     clear_error();
707     sock->pmask &= ~FD_ACCEPT;
708     sock->hmask &= ~FD_ACCEPT;
709     sock_reselect( sock );
710     release_object( sock );
711     return acceptsock;
712 }
713
714 /* set the last error depending on errno */
715 static int sock_get_error( int err )
716 {
717     switch (err)
718     {
719         case EINTR:             return WSAEINTR;
720         case EBADF:             return WSAEBADF;
721         case EPERM:
722         case EACCES:            return WSAEACCES;
723         case EFAULT:            return WSAEFAULT;
724         case EINVAL:            return WSAEINVAL;
725         case EMFILE:            return WSAEMFILE;
726         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
727         case EINPROGRESS:       return WSAEINPROGRESS;
728         case EALREADY:          return WSAEALREADY;
729         case ENOTSOCK:          return WSAENOTSOCK;
730         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
731         case EMSGSIZE:          return WSAEMSGSIZE;
732         case EPROTOTYPE:        return WSAEPROTOTYPE;
733         case ENOPROTOOPT:       return WSAENOPROTOOPT;
734         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
735         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
736         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
737         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
738         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
739         case EADDRINUSE:        return WSAEADDRINUSE;
740         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
741         case ENETDOWN:          return WSAENETDOWN;
742         case ENETUNREACH:       return WSAENETUNREACH;
743         case ENETRESET:         return WSAENETRESET;
744         case ECONNABORTED:      return WSAECONNABORTED;
745         case EPIPE:
746         case ECONNRESET:        return WSAECONNRESET;
747         case ENOBUFS:           return WSAENOBUFS;
748         case EISCONN:           return WSAEISCONN;
749         case ENOTCONN:          return WSAENOTCONN;
750         case ESHUTDOWN:         return WSAESHUTDOWN;
751         case ETOOMANYREFS:      return WSAETOOMANYREFS;
752         case ETIMEDOUT:         return WSAETIMEDOUT;
753         case ECONNREFUSED:      return WSAECONNREFUSED;
754         case ELOOP:             return WSAELOOP;
755         case ENAMETOOLONG:      return WSAENAMETOOLONG;
756         case EHOSTDOWN:         return WSAEHOSTDOWN;
757         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
758         case ENOTEMPTY:         return WSAENOTEMPTY;
759 #ifdef EPROCLIM
760         case EPROCLIM:          return WSAEPROCLIM;
761 #endif
762 #ifdef EUSERS
763         case EUSERS:            return WSAEUSERS;
764 #endif
765 #ifdef EDQUOT
766         case EDQUOT:            return WSAEDQUOT;
767 #endif
768 #ifdef ESTALE
769         case ESTALE:            return WSAESTALE;
770 #endif
771 #ifdef EREMOTE
772         case EREMOTE:           return WSAEREMOTE;
773 #endif
774     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
775     }
776 }
777
778 /* set the last error depending on errno */
779 static void sock_set_error(void)
780 {
781     set_error( sock_get_error( errno ) );
782 }
783
784 /* create a socket */
785 DECL_HANDLER(create_socket)
786 {
787     struct object *obj;
788
789     reply->handle = 0;
790     if ((obj = create_socket( req->family, req->type, req->protocol, req->flags )) != NULL)
791     {
792         reply->handle = alloc_handle( current->process, obj, req->access, req->attributes );
793         release_object( obj );
794     }
795 }
796
797 /* accept a socket */
798 DECL_HANDLER(accept_socket)
799 {
800     struct sock *sock;
801
802     reply->handle = 0;
803     if ((sock = accept_socket( req->lhandle )) != NULL)
804     {
805         reply->handle = alloc_handle( current->process, &sock->obj, req->access, req->attributes );
806         sock->wparam = reply->handle;  /* wparam for message is the socket handle */
807         sock_reselect( sock );
808         release_object( &sock->obj );
809     }
810 }
811
812 /* set socket event parameters */
813 DECL_HANDLER(set_socket_event)
814 {
815     struct sock *sock;
816     struct event *old_event;
817     int pollev;
818
819     if (!(sock = (struct sock *)get_handle_obj( current->process, req->handle,
820                                                 FILE_WRITE_ATTRIBUTES, &sock_ops))) return;
821     old_event = sock->event;
822     sock->mask    = req->mask;
823     sock->hmask   &= ~req->mask; /* re-enable held events */
824     sock->event   = NULL;
825     sock->window  = req->window;
826     sock->message = req->msg;
827     sock->wparam  = req->handle;  /* wparam is the socket handle */
828     if (req->event) sock->event = get_event_obj( current->process, req->event, EVENT_MODIFY_STATE );
829
830     if (debug_level && sock->event) fprintf(stderr, "event ptr: %p\n", sock->event);
831
832     pollev = sock_reselect( sock );
833     if ( pollev ) sock_try_event( sock, pollev );
834
835     if (sock->mask)
836         sock->state |= FD_WINE_NONBLOCKING;
837
838     /* if a network event is pending, signal the event object
839        it is possible that FD_CONNECT or FD_ACCEPT network events has happened
840        before a WSAEventSelect() was done on it.
841        (when dealing with Asynchronous socket)  */
842     if (sock->pmask & sock->mask) sock_wake_up( sock, pollev );
843
844     if (old_event) release_object( old_event ); /* we're through with it */
845     release_object( &sock->obj );
846 }
847
848 /* get socket event parameters */
849 DECL_HANDLER(get_socket_event)
850 {
851     struct sock *sock;
852
853     sock = (struct sock *)get_handle_obj( current->process, req->handle, FILE_READ_ATTRIBUTES, &sock_ops );
854     if (!sock)
855     {
856         reply->mask  = 0;
857         reply->pmask = 0;
858         reply->state = 0;
859         set_error( WSAENOTSOCK );
860         return;
861     }
862     reply->mask  = sock->mask;
863     reply->pmask = sock->pmask;
864     reply->state = sock->state;
865     set_reply_data( sock->errors, min( get_reply_max_size(), sizeof(sock->errors) ));
866
867     if (req->service)
868     {
869         if (req->c_event)
870         {
871             struct event *cevent = get_event_obj( current->process, req->c_event,
872                                                   EVENT_MODIFY_STATE );
873             if (cevent)
874             {
875                 reset_event( cevent );
876                 release_object( cevent );
877             }
878         }
879         sock->pmask = 0;
880         sock_reselect( sock );
881     }
882     release_object( &sock->obj );
883 }
884
885 /* re-enable pending socket events */
886 DECL_HANDLER(enable_socket_event)
887 {
888     struct sock *sock;
889     int pollev;
890
891     if (!(sock = (struct sock*)get_handle_obj( current->process, req->handle,
892                                                FILE_WRITE_ATTRIBUTES, &sock_ops)))
893         return;
894
895     sock->pmask &= ~req->mask; /* is this safe? */
896     sock->hmask &= ~req->mask;
897     if ( req->mask & FD_READ )
898         sock->hmask &= ~FD_CLOSE;
899     sock->state |= req->sstate;
900     sock->state &= ~req->cstate;
901     if ( sock->type != SOCK_STREAM ) sock->state &= ~STREAM_FLAG_MASK;
902
903     pollev = sock_reselect( sock );
904     if ( pollev ) sock_try_event( sock, pollev );
905
906     release_object( &sock->obj );
907 }
908
909 DECL_HANDLER(set_socket_deferred)
910 {
911     struct sock *sock, *acceptsock;
912
913     sock=(struct sock *)get_handle_obj( current->process, req->handle, FILE_WRITE_ATTRIBUTES, &sock_ops );
914     if ( !sock )
915     {
916         set_error( WSAENOTSOCK );
917         return;
918     }
919     acceptsock = (struct sock *)get_handle_obj( current->process, req->deferred, 0, &sock_ops );
920     if ( !acceptsock )
921     {
922         release_object( sock );
923         set_error( WSAENOTSOCK );
924         return;
925     }
926     sock->deferred = acceptsock;
927     release_object( sock );
928 }