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