crypt32: Use property list for decoded message parameters.
[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_fd_type( struct fd *fd );
99 static void sock_queue_async( struct fd *fd, const async_data_t *data, int type, int count );
100 static void sock_reselect_async( struct fd *fd, struct async_queue *queue );
101 static void sock_cancel_async( struct fd *fd );
102
103 static int sock_get_error( int err );
104 static void sock_set_error(void);
105
106 static const struct object_ops sock_ops =
107 {
108     sizeof(struct sock),          /* size */
109     sock_dump,                    /* dump */
110     add_queue,                    /* add_queue */
111     remove_queue,                 /* remove_queue */
112     sock_signaled,                /* signaled */
113     no_satisfied,                 /* satisfied */
114     no_signal,                    /* signal */
115     sock_get_fd,                  /* get_fd */
116     sock_map_access,              /* map_access */
117     no_lookup_name,               /* lookup_name */
118     no_open_file,                 /* open_file */
119     fd_close_handle,              /* close_handle */
120     sock_destroy                  /* destroy */
121 };
122
123 static const struct fd_ops sock_fd_ops =
124 {
125     sock_get_poll_events,         /* get_poll_events */
126     sock_poll_event,              /* poll_event */
127     no_flush,                     /* flush */
128     sock_get_fd_type,             /* get_file_info */
129     default_fd_ioctl,             /* ioctl */
130     sock_queue_async,             /* queue_async */
131     sock_reselect_async,          /* reselect_async */
132     sock_cancel_async             /* cancel_async */
133 };
134
135
136 /* Permutation of 0..FD_MAX_EVENTS - 1 representing the order in which
137  * we post messages if there are multiple events.  Used to send
138  * messages.  The problem is if there is both a FD_CONNECT event and,
139  * say, an FD_READ event available on the same socket, we want to
140  * notify the app of the connect event first.  Otherwise it may
141  * discard the read event because it thinks it hasn't connected yet.
142  */
143 static const int event_bitorder[FD_MAX_EVENTS] =
144 {
145     FD_CONNECT_BIT,
146     FD_ACCEPT_BIT,
147     FD_OOB_BIT,
148     FD_WRITE_BIT,
149     FD_READ_BIT,
150     FD_CLOSE_BIT,
151     6, 7, 8, 9  /* leftovers */
152 };
153
154 /* Flags that make sense only for SOCK_STREAM sockets */
155 #define STREAM_FLAG_MASK ((unsigned int) (FD_CONNECT | FD_ACCEPT | FD_WINE_LISTENING | FD_WINE_CONNECTED))
156
157 typedef enum {
158     SOCK_SHUTDOWN_ERROR = -1,
159     SOCK_SHUTDOWN_EOF = 0,
160     SOCK_SHUTDOWN_POLLHUP = 1
161 } sock_shutdown_t;
162
163 static sock_shutdown_t sock_shutdown_type = SOCK_SHUTDOWN_ERROR;
164
165 static sock_shutdown_t sock_check_pollhup(void)
166 {
167     sock_shutdown_t ret = SOCK_SHUTDOWN_ERROR;
168     int fd[2], n;
169     struct pollfd pfd;
170     char dummy;
171
172     if ( socketpair( AF_UNIX, SOCK_STREAM, 0, fd ) ) goto out;
173     if ( shutdown( fd[0], 1 ) ) goto out;
174
175     pfd.fd = fd[1];
176     pfd.events = POLLIN;
177     pfd.revents = 0;
178
179     n = poll( &pfd, 1, 0 );
180     if ( n != 1 ) goto out; /* error or timeout */
181     if ( pfd.revents & POLLHUP )
182         ret = SOCK_SHUTDOWN_POLLHUP;
183     else if ( pfd.revents & POLLIN &&
184               read( fd[1], &dummy, 1 ) == 0 )
185         ret = SOCK_SHUTDOWN_EOF;
186
187 out:
188     close( fd[0] );
189     close( fd[1] );
190     return ret;
191 }
192
193 void sock_init(void)
194 {
195     sock_shutdown_type = sock_check_pollhup();
196
197     switch ( sock_shutdown_type )
198     {
199     case SOCK_SHUTDOWN_EOF:
200         if (debug_level) fprintf( stderr, "sock_init: shutdown() causes EOF\n" );
201         break;
202     case SOCK_SHUTDOWN_POLLHUP:
203         if (debug_level) fprintf( stderr, "sock_init: shutdown() causes POLLHUP\n" );
204         break;
205     default:
206         fprintf( stderr, "sock_init: ERROR in sock_check_pollhup()\n" );
207         sock_shutdown_type = SOCK_SHUTDOWN_EOF;
208     }
209 }
210
211 static int sock_reselect( struct sock *sock )
212 {
213     int ev = sock_get_poll_events( sock->fd );
214
215     if (debug_level)
216         fprintf(stderr,"sock_reselect(%p): new mask %x\n", sock, ev);
217
218     if (!sock->polling)  /* FIXME: should find a better way to do this */
219     {
220         /* previously unconnected socket, is this reselect supposed to connect it? */
221         if (!(sock->state & ~FD_WINE_NONBLOCKING)) return 0;
222         /* ok, it is, attach it to the wineserver's main poll loop */
223         sock->polling = 1;
224     }
225     /* update condition mask */
226     set_fd_events( sock->fd, ev );
227     return ev;
228 }
229
230 /* After POLLHUP is received, the socket will no longer be in the main select loop.
231    This function is used to signal pending events nevertheless */
232 static void sock_try_event( struct sock *sock, int event )
233 {
234     event = check_fd_events( sock->fd, event );
235     if (event)
236     {
237         if ( debug_level ) fprintf( stderr, "sock_try_event: %x\n", event );
238         sock_poll_event( sock->fd, event );
239     }
240 }
241
242 /* wake anybody waiting on the socket event or send the associated message */
243 static void sock_wake_up( struct sock *sock, int pollev )
244 {
245     unsigned int events = sock->pmask & sock->mask;
246     int i;
247     int async_active = 0;
248
249     if ( pollev & (POLLIN|POLLPRI) && async_waiting( sock->read_q ))
250     {
251         if (debug_level) fprintf( stderr, "activating read queue for socket %p\n", sock );
252         async_wake_up( sock->read_q, STATUS_ALERTED );
253         async_active = 1;
254     }
255     if ( pollev & POLLOUT && async_waiting( sock->write_q ))
256     {
257         if (debug_level) fprintf( stderr, "activating write queue for socket %p\n", sock );
258         async_wake_up( sock->write_q, STATUS_ALERTED );
259         async_active = 1;
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  || async_waiting( sock->read_q )) ev |= POLLIN | POLLPRI;
487     if (mask & FD_WRITE || async_waiting( sock->write_q )) ev |= POLLOUT;
488     /* We use POLLIN with 0 bytes recv() as FD_CLOSE indication for stream sockets. */
489     if ( sock->type == SOCK_STREAM && ( sock->mask & ~sock->hmask & FD_CLOSE) )
490         ev |= POLLIN;
491
492     return ev;
493 }
494
495 static enum server_fd_type sock_get_fd_type( struct fd *fd )
496 {
497     return FD_TYPE_SOCKET;
498 }
499
500 static void sock_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
501 {
502     struct sock *sock = get_fd_user( fd );
503     struct async_queue *queue;
504     int pollev;
505
506     assert( sock->obj.ops == &sock_ops );
507
508     switch (type)
509     {
510     case ASYNC_TYPE_READ:
511         if (!sock->read_q && !(sock->read_q = create_async_queue( sock->fd ))) return;
512         queue = sock->read_q;
513         sock->hmask &= ~FD_CLOSE;
514         break;
515     case ASYNC_TYPE_WRITE:
516         if (!sock->write_q && !(sock->write_q = create_async_queue( sock->fd ))) return;
517         queue = sock->write_q;
518         break;
519     default:
520         set_error( STATUS_INVALID_PARAMETER );
521         return;
522     }
523
524     if ( ( !( sock->state & FD_READ ) && type == ASYNC_TYPE_READ  ) ||
525          ( !( sock->state & FD_WRITE ) && type == ASYNC_TYPE_WRITE ) )
526     {
527         set_error( STATUS_PIPE_DISCONNECTED );
528     }
529     else
530     {
531         struct async *async;
532         if (!(async = create_async( current, queue, data ))) return;
533         release_object( async );
534         set_error( STATUS_PENDING );
535     }
536
537     pollev = sock_reselect( sock );
538     if ( pollev ) sock_try_event( sock, pollev );
539 }
540
541 static void sock_reselect_async( struct fd *fd, struct async_queue *queue )
542 {
543     struct sock *sock = get_fd_user( fd );
544     int events = sock_reselect( sock );
545     if (events) sock_try_event( sock, events );
546 }
547
548 static void sock_cancel_async( struct fd *fd )
549 {
550     struct sock *sock = get_fd_user( fd );
551     assert( sock->obj.ops == &sock_ops );
552
553     async_wake_up( sock->read_q, STATUS_CANCELLED );
554     async_wake_up( sock->write_q, STATUS_CANCELLED );
555 }
556
557 static struct fd *sock_get_fd( struct object *obj )
558 {
559     struct sock *sock = (struct sock *)obj;
560     return (struct fd *)grab_object( sock->fd );
561 }
562
563 static void sock_destroy( struct object *obj )
564 {
565     struct sock *sock = (struct sock *)obj;
566     assert( obj->ops == &sock_ops );
567
568     /* FIXME: special socket shutdown stuff? */
569
570     if ( sock->deferred )
571         release_object( sock->deferred );
572
573     free_async_queue( sock->read_q );
574     free_async_queue( sock->write_q );
575     if (sock->event) release_object( sock->event );
576     if (sock->fd)
577     {
578         /* shut the socket down to force pending poll() calls in the client to return */
579         shutdown( get_unix_fd(sock->fd), SHUT_RDWR );
580         release_object( sock->fd );
581     }
582 }
583
584 /* create a new and unconnected socket */
585 static struct object *create_socket( int family, int type, int protocol, unsigned int flags )
586 {
587     struct sock *sock;
588     int sockfd;
589
590     sockfd = socket( family, type, protocol );
591     if (debug_level)
592         fprintf(stderr,"socket(%d,%d,%d)=%d\n",family,type,protocol,sockfd);
593     if (sockfd == -1)
594     {
595         sock_set_error();
596         return NULL;
597     }
598     fcntl(sockfd, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
599     if (!(sock = alloc_object( &sock_ops )))
600     {
601         close( sockfd );
602         return NULL;
603     }
604     sock->state = (type != SOCK_STREAM) ? (FD_READ|FD_WRITE) : 0;
605     sock->mask    = 0;
606     sock->hmask   = 0;
607     sock->pmask   = 0;
608     sock->polling = 0;
609     sock->flags   = flags;
610     sock->type    = type;
611     sock->family  = family;
612     sock->event   = NULL;
613     sock->window  = 0;
614     sock->message = 0;
615     sock->wparam  = 0;
616     sock->deferred = NULL;
617     sock->read_q  = NULL;
618     sock->write_q = NULL;
619     if (!(sock->fd = create_anonymous_fd( &sock_fd_ops, sockfd, &sock->obj,
620                             (flags & WSA_FLAG_OVERLAPPED) ? 0 : FILE_SYNCHRONOUS_IO_NONALERT )))
621     {
622         release_object( sock );
623         return NULL;
624     }
625     sock_reselect( sock );
626     clear_error();
627     return &sock->obj;
628 }
629
630 /* accept a socket (creates a new fd) */
631 static struct sock *accept_socket( obj_handle_t handle )
632 {
633     struct sock *acceptsock;
634     struct sock *sock;
635     int acceptfd;
636     struct sockaddr     saddr;
637
638     sock = (struct sock *)get_handle_obj( current->process, handle, FILE_READ_DATA, &sock_ops );
639     if (!sock)
640         return NULL;
641
642     if ( sock->deferred )
643     {
644         acceptsock = sock->deferred;
645         sock->deferred = NULL;
646     }
647     else
648     {
649
650         /* Try to accept(2). We can't be safe that this an already connected socket
651          * or that accept() is allowed on it. In those cases we will get -1/errno
652          * return.
653          */
654         unsigned int slen = sizeof(saddr);
655         acceptfd = accept( get_unix_fd(sock->fd), &saddr, &slen);
656         if (acceptfd==-1)
657         {
658             sock_set_error();
659             release_object( sock );
660             return NULL;
661         }
662         if (!(acceptsock = alloc_object( &sock_ops )))
663         {
664             close( acceptfd );
665             release_object( sock );
666             return NULL;
667         }
668
669         /* newly created socket gets the same properties of the listening socket */
670         fcntl(acceptfd, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
671         acceptsock->state  = FD_WINE_CONNECTED|FD_READ|FD_WRITE;
672         if (sock->state & FD_WINE_NONBLOCKING)
673             acceptsock->state |= FD_WINE_NONBLOCKING;
674         acceptsock->mask    = sock->mask;
675         acceptsock->hmask   = 0;
676         acceptsock->pmask   = 0;
677         acceptsock->polling = 0;
678         acceptsock->type    = sock->type;
679         acceptsock->family  = sock->family;
680         acceptsock->event   = NULL;
681         acceptsock->window  = sock->window;
682         acceptsock->message = sock->message;
683         acceptsock->wparam  = 0;
684         if (sock->event) acceptsock->event = (struct event *)grab_object( sock->event );
685         acceptsock->flags = sock->flags;
686         acceptsock->deferred = NULL;
687         acceptsock->read_q  = NULL;
688         acceptsock->write_q = NULL;
689         if (!(acceptsock->fd = create_anonymous_fd( &sock_fd_ops, acceptfd, &acceptsock->obj,
690                                                     get_fd_options( sock->fd ) )))
691         {
692             release_object( acceptsock );
693             release_object( sock );
694             return NULL;
695         }
696     }
697     clear_error();
698     sock->pmask &= ~FD_ACCEPT;
699     sock->hmask &= ~FD_ACCEPT;
700     sock_reselect( sock );
701     release_object( sock );
702     return acceptsock;
703 }
704
705 /* set the last error depending on errno */
706 static int sock_get_error( int err )
707 {
708     switch (err)
709     {
710         case EINTR:             return WSAEINTR;
711         case EBADF:             return WSAEBADF;
712         case EPERM:
713         case EACCES:            return WSAEACCES;
714         case EFAULT:            return WSAEFAULT;
715         case EINVAL:            return WSAEINVAL;
716         case EMFILE:            return WSAEMFILE;
717         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
718         case EINPROGRESS:       return WSAEINPROGRESS;
719         case EALREADY:          return WSAEALREADY;
720         case ENOTSOCK:          return WSAENOTSOCK;
721         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
722         case EMSGSIZE:          return WSAEMSGSIZE;
723         case EPROTOTYPE:        return WSAEPROTOTYPE;
724         case ENOPROTOOPT:       return WSAENOPROTOOPT;
725         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
726         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
727         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
728         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
729         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
730         case EADDRINUSE:        return WSAEADDRINUSE;
731         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
732         case ENETDOWN:          return WSAENETDOWN;
733         case ENETUNREACH:       return WSAENETUNREACH;
734         case ENETRESET:         return WSAENETRESET;
735         case ECONNABORTED:      return WSAECONNABORTED;
736         case EPIPE:
737         case ECONNRESET:        return WSAECONNRESET;
738         case ENOBUFS:           return WSAENOBUFS;
739         case EISCONN:           return WSAEISCONN;
740         case ENOTCONN:          return WSAENOTCONN;
741         case ESHUTDOWN:         return WSAESHUTDOWN;
742         case ETOOMANYREFS:      return WSAETOOMANYREFS;
743         case ETIMEDOUT:         return WSAETIMEDOUT;
744         case ECONNREFUSED:      return WSAECONNREFUSED;
745         case ELOOP:             return WSAELOOP;
746         case ENAMETOOLONG:      return WSAENAMETOOLONG;
747         case EHOSTDOWN:         return WSAEHOSTDOWN;
748         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
749         case ENOTEMPTY:         return WSAENOTEMPTY;
750 #ifdef EPROCLIM
751         case EPROCLIM:          return WSAEPROCLIM;
752 #endif
753 #ifdef EUSERS
754         case EUSERS:            return WSAEUSERS;
755 #endif
756 #ifdef EDQUOT
757         case EDQUOT:            return WSAEDQUOT;
758 #endif
759 #ifdef ESTALE
760         case ESTALE:            return WSAESTALE;
761 #endif
762 #ifdef EREMOTE
763         case EREMOTE:           return WSAEREMOTE;
764 #endif
765     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
766     }
767 }
768
769 /* set the last error depending on errno */
770 static void sock_set_error(void)
771 {
772     set_error( sock_get_error( errno ) );
773 }
774
775 /* create a socket */
776 DECL_HANDLER(create_socket)
777 {
778     struct object *obj;
779
780     reply->handle = 0;
781     if ((obj = create_socket( req->family, req->type, req->protocol, req->flags )) != NULL)
782     {
783         reply->handle = alloc_handle( current->process, obj, req->access, req->attributes );
784         release_object( obj );
785     }
786 }
787
788 /* accept a socket */
789 DECL_HANDLER(accept_socket)
790 {
791     struct sock *sock;
792
793     reply->handle = 0;
794     if ((sock = accept_socket( req->lhandle )) != NULL)
795     {
796         reply->handle = alloc_handle( current->process, &sock->obj, req->access, req->attributes );
797         sock->wparam = reply->handle;  /* wparam for message is the socket handle */
798         sock_reselect( sock );
799         release_object( &sock->obj );
800     }
801 }
802
803 /* set socket event parameters */
804 DECL_HANDLER(set_socket_event)
805 {
806     struct sock *sock;
807     struct event *old_event;
808     int pollev;
809
810     if (!(sock = (struct sock *)get_handle_obj( current->process, req->handle,
811                                                 FILE_WRITE_ATTRIBUTES, &sock_ops))) return;
812     old_event = sock->event;
813     sock->mask    = req->mask;
814     sock->hmask   &= ~req->mask; /* re-enable held events */
815     sock->event   = NULL;
816     sock->window  = req->window;
817     sock->message = req->msg;
818     sock->wparam  = req->handle;  /* wparam is the socket handle */
819     if (req->event) sock->event = get_event_obj( current->process, req->event, EVENT_MODIFY_STATE );
820
821     if (debug_level && sock->event) fprintf(stderr, "event ptr: %p\n", sock->event);
822
823     pollev = sock_reselect( sock );
824     if ( pollev ) sock_try_event( sock, pollev );
825
826     if (sock->mask)
827         sock->state |= FD_WINE_NONBLOCKING;
828
829     /* if a network event is pending, signal the event object
830        it is possible that FD_CONNECT or FD_ACCEPT network events has happened
831        before a WSAEventSelect() was done on it.
832        (when dealing with Asynchronous socket)  */
833     if (sock->pmask & sock->mask) sock_wake_up( sock, pollev );
834
835     if (old_event) release_object( old_event ); /* we're through with it */
836     release_object( &sock->obj );
837 }
838
839 /* get socket event parameters */
840 DECL_HANDLER(get_socket_event)
841 {
842     struct sock *sock;
843
844     sock = (struct sock *)get_handle_obj( current->process, req->handle, FILE_READ_ATTRIBUTES, &sock_ops );
845     if (!sock)
846     {
847         reply->mask  = 0;
848         reply->pmask = 0;
849         reply->state = 0;
850         set_error( WSAENOTSOCK );
851         return;
852     }
853     reply->mask  = sock->mask;
854     reply->pmask = sock->pmask;
855     reply->state = sock->state;
856     set_reply_data( sock->errors, min( get_reply_max_size(), sizeof(sock->errors) ));
857
858     if (req->service)
859     {
860         if (req->c_event)
861         {
862             struct event *cevent = get_event_obj( current->process, req->c_event,
863                                                   EVENT_MODIFY_STATE );
864             if (cevent)
865             {
866                 reset_event( cevent );
867                 release_object( cevent );
868             }
869         }
870         sock->pmask = 0;
871         sock_reselect( sock );
872     }
873     release_object( &sock->obj );
874 }
875
876 /* re-enable pending socket events */
877 DECL_HANDLER(enable_socket_event)
878 {
879     struct sock *sock;
880     int pollev;
881
882     if (!(sock = (struct sock*)get_handle_obj( current->process, req->handle,
883                                                FILE_WRITE_ATTRIBUTES, &sock_ops)))
884         return;
885
886     sock->pmask &= ~req->mask; /* is this safe? */
887     sock->hmask &= ~req->mask;
888     if ( req->mask & FD_READ )
889         sock->hmask &= ~FD_CLOSE;
890     sock->state |= req->sstate;
891     sock->state &= ~req->cstate;
892     if ( sock->type != SOCK_STREAM ) sock->state &= ~STREAM_FLAG_MASK;
893
894     pollev = sock_reselect( sock );
895     if ( pollev ) sock_try_event( sock, pollev );
896
897     release_object( &sock->obj );
898 }
899
900 DECL_HANDLER(set_socket_deferred)
901 {
902     struct sock *sock, *acceptsock;
903
904     sock=(struct sock *)get_handle_obj( current->process, req->handle, FILE_WRITE_ATTRIBUTES, &sock_ops );
905     if ( !sock )
906     {
907         set_error( WSAENOTSOCK );
908         return;
909     }
910     acceptsock = (struct sock *)get_handle_obj( current->process, req->deferred, 0, &sock_ops );
911     if ( !acceptsock )
912     {
913         release_object( sock );
914         set_error( WSAENOTSOCK );
915         return;
916     }
917     sock->deferred = acceptsock;
918     release_object( sock );
919 }