ntdll: Implement the NamedPipeConfiguration value for the FilePipeLocalInformation...
[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 #include "winerror.h"
55
56 #include "process.h"
57 #include "file.h"
58 #include "handle.h"
59 #include "thread.h"
60 #include "request.h"
61 #include "user.h"
62
63 /* From winsock.h */
64 #define FD_MAX_EVENTS              10
65 #define FD_READ_BIT                0
66 #define FD_WRITE_BIT               1
67 #define FD_OOB_BIT                 2
68 #define FD_ACCEPT_BIT              3
69 #define FD_CONNECT_BIT             4
70 #define FD_CLOSE_BIT               5
71
72 /*
73  * Define flags to be used with the WSAAsyncSelect() call.
74  */
75 #define FD_READ                    0x00000001
76 #define FD_WRITE                   0x00000002
77 #define FD_OOB                     0x00000004
78 #define FD_ACCEPT                  0x00000008
79 #define FD_CONNECT                 0x00000010
80 #define FD_CLOSE                   0x00000020
81
82 /* internal per-socket flags */
83 #define FD_WINE_LISTENING          0x10000000
84 #define FD_WINE_NONBLOCKING        0x20000000
85 #define FD_WINE_CONNECTED          0x40000000
86 #define FD_WINE_RAW                0x80000000
87 #define FD_WINE_INTERNAL           0xFFFF0000
88
89 /* Constants for WSAIoctl() */
90 #define WSA_FLAG_OVERLAPPED        0x01
91
92 struct sock
93 {
94     struct object       obj;         /* object header */
95     struct fd          *fd;          /* socket file descriptor */
96     unsigned int        state;       /* status bits */
97     unsigned int        mask;        /* event mask */
98     unsigned int        hmask;       /* held (blocked) events */
99     unsigned int        pmask;       /* pending events */
100     unsigned int        flags;       /* socket flags */
101     int                 polling;     /* is socket being polled? */
102     unsigned short      type;        /* socket type */
103     unsigned short      family;      /* socket family */
104     struct event       *event;       /* event object */
105     user_handle_t       window;      /* window to send the message to */
106     unsigned int        message;     /* message to send */
107     obj_handle_t        wparam;      /* message wparam (socket handle) */
108     int                 errors[FD_MAX_EVENTS]; /* event errors */
109     struct sock        *deferred;    /* socket that waits for a deferred accept */
110     struct async_queue *read_q;      /* queue for asynchronous reads */
111     struct async_queue *write_q;     /* queue for asynchronous writes */
112 };
113
114 static void sock_dump( struct object *obj, int verbose );
115 static int sock_signaled( struct object *obj, struct thread *thread );
116 static struct fd *sock_get_fd( struct object *obj );
117 static void sock_destroy( struct object *obj );
118
119 static int sock_get_poll_events( struct fd *fd );
120 static void sock_poll_event( struct fd *fd, int event );
121 static enum server_fd_type sock_get_fd_type( struct fd *fd );
122 static void sock_queue_async( struct fd *fd, const async_data_t *data, int type, int count );
123 static void sock_reselect_async( struct fd *fd, struct async_queue *queue );
124 static void sock_cancel_async( struct fd *fd, struct process *process, struct thread *thread, client_ptr_t iosb );
125
126 static int sock_get_ntstatus( int err );
127 static int sock_get_error( int err );
128 static void sock_set_error(void);
129
130 static const struct object_ops sock_ops =
131 {
132     sizeof(struct sock),          /* size */
133     sock_dump,                    /* dump */
134     no_get_type,                  /* get_type */
135     add_queue,                    /* add_queue */
136     remove_queue,                 /* remove_queue */
137     sock_signaled,                /* signaled */
138     no_satisfied,                 /* satisfied */
139     no_signal,                    /* signal */
140     sock_get_fd,                  /* get_fd */
141     default_fd_map_access,        /* map_access */
142     default_get_sd,               /* get_sd */
143     default_set_sd,               /* set_sd */
144     no_lookup_name,               /* lookup_name */
145     no_open_file,                 /* open_file */
146     fd_close_handle,              /* close_handle */
147     sock_destroy                  /* destroy */
148 };
149
150 static const struct fd_ops sock_fd_ops =
151 {
152     sock_get_poll_events,         /* get_poll_events */
153     sock_poll_event,              /* poll_event */
154     no_flush,                     /* flush */
155     sock_get_fd_type,             /* get_fd_type */
156     default_fd_ioctl,             /* ioctl */
157     sock_queue_async,             /* queue_async */
158     sock_reselect_async,          /* reselect_async */
159     sock_cancel_async             /* cancel_async */
160 };
161
162
163 /* Permutation of 0..FD_MAX_EVENTS - 1 representing the order in which
164  * we post messages if there are multiple events.  Used to send
165  * messages.  The problem is if there is both a FD_CONNECT event and,
166  * say, an FD_READ event available on the same socket, we want to
167  * notify the app of the connect event first.  Otherwise it may
168  * discard the read event because it thinks it hasn't connected yet.
169  */
170 static const int event_bitorder[FD_MAX_EVENTS] =
171 {
172     FD_CONNECT_BIT,
173     FD_ACCEPT_BIT,
174     FD_OOB_BIT,
175     FD_WRITE_BIT,
176     FD_READ_BIT,
177     FD_CLOSE_BIT,
178     6, 7, 8, 9  /* leftovers */
179 };
180
181 /* Flags that make sense only for SOCK_STREAM sockets */
182 #define STREAM_FLAG_MASK ((unsigned int) (FD_CONNECT | FD_ACCEPT | FD_WINE_LISTENING | FD_WINE_CONNECTED))
183
184 typedef enum {
185     SOCK_SHUTDOWN_ERROR = -1,
186     SOCK_SHUTDOWN_EOF = 0,
187     SOCK_SHUTDOWN_POLLHUP = 1
188 } sock_shutdown_t;
189
190 static sock_shutdown_t sock_shutdown_type = SOCK_SHUTDOWN_ERROR;
191
192 static sock_shutdown_t sock_check_pollhup(void)
193 {
194     sock_shutdown_t ret = SOCK_SHUTDOWN_ERROR;
195     int fd[2], n;
196     struct pollfd pfd;
197     char dummy;
198
199     if ( socketpair( AF_UNIX, SOCK_STREAM, 0, fd ) ) goto out;
200     if ( shutdown( fd[0], 1 ) ) goto out;
201
202     pfd.fd = fd[1];
203     pfd.events = POLLIN;
204     pfd.revents = 0;
205
206     /* Solaris' poll() sometimes returns nothing if given a 0ms timeout here */
207     n = poll( &pfd, 1, 1 );
208     if ( n != 1 ) goto out; /* error or timeout */
209     if ( pfd.revents & POLLHUP )
210         ret = SOCK_SHUTDOWN_POLLHUP;
211     else if ( pfd.revents & POLLIN &&
212               read( fd[1], &dummy, 1 ) == 0 )
213         ret = SOCK_SHUTDOWN_EOF;
214
215 out:
216     close( fd[0] );
217     close( fd[1] );
218     return ret;
219 }
220
221 void sock_init(void)
222 {
223     sock_shutdown_type = sock_check_pollhup();
224
225     switch ( sock_shutdown_type )
226     {
227     case SOCK_SHUTDOWN_EOF:
228         if (debug_level) fprintf( stderr, "sock_init: shutdown() causes EOF\n" );
229         break;
230     case SOCK_SHUTDOWN_POLLHUP:
231         if (debug_level) fprintf( stderr, "sock_init: shutdown() causes POLLHUP\n" );
232         break;
233     default:
234         fprintf( stderr, "sock_init: ERROR in sock_check_pollhup()\n" );
235         sock_shutdown_type = SOCK_SHUTDOWN_EOF;
236     }
237 }
238
239 static int sock_reselect( struct sock *sock )
240 {
241     int ev = sock_get_poll_events( sock->fd );
242
243     if (debug_level)
244         fprintf(stderr,"sock_reselect(%p): new mask %x\n", sock, ev);
245
246     if (!sock->polling)  /* FIXME: should find a better way to do this */
247     {
248         /* previously unconnected socket, is this reselect supposed to connect it? */
249         if (!(sock->state & ~FD_WINE_NONBLOCKING)) return 0;
250         /* ok, it is, attach it to the wineserver's main poll loop */
251         sock->polling = 1;
252         allow_fd_caching( sock->fd );
253     }
254     /* update condition mask */
255     set_fd_events( sock->fd, ev );
256     return ev;
257 }
258
259 /* wake anybody waiting on the socket event or send the associated message */
260 static void sock_wake_up( struct sock *sock )
261 {
262     unsigned int events = sock->pmask & sock->mask;
263     int i;
264
265     if ( !events ) return;
266
267     if (sock->event)
268     {
269         if (debug_level) fprintf(stderr, "signalling events %x ptr %p\n", events, sock->event );
270         set_event( sock->event );
271     }
272     if (sock->window)
273     {
274         if (debug_level) fprintf(stderr, "signalling events %x win %08x\n", events, sock->window );
275         for (i = 0; i < FD_MAX_EVENTS; i++)
276         {
277             int event = event_bitorder[i];
278             if (sock->pmask & (1 << event))
279             {
280                 lparam_t lparam = (1 << event) | (sock_get_error(sock->errors[event]) << 16);
281                 post_message( sock->window, sock->message, sock->wparam, lparam );
282             }
283         }
284         sock->pmask = 0;
285         sock_reselect( sock );
286     }
287 }
288
289 static inline int sock_error( struct fd *fd )
290 {
291     unsigned int optval = 0, optlen;
292
293     optlen = sizeof(optval);
294     getsockopt( get_unix_fd(fd), SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
295     return optval;
296 }
297
298 static int sock_dispatch_asyncs( struct sock *sock, int event, int error )
299 {
300     if ( sock->flags & WSA_FLAG_OVERLAPPED )
301     {
302         if ( event & (POLLIN|POLLPRI) && async_waiting( sock->read_q ) )
303         {
304             if (debug_level) fprintf( stderr, "activating read queue for socket %p\n", sock );
305             async_wake_up( sock->read_q, STATUS_ALERTED );
306             event &= ~(POLLIN|POLLPRI);
307         }
308         if ( event & POLLOUT && async_waiting( sock->write_q ) )
309         {
310             if (debug_level) fprintf( stderr, "activating write queue for socket %p\n", sock );
311             async_wake_up( sock->write_q, STATUS_ALERTED );
312             event &= ~POLLOUT;
313         }
314         if ( event & (POLLERR|POLLHUP) )
315         {
316             int status = sock_get_ntstatus( error );
317
318             if ( !(sock->state & FD_READ) )
319                 async_wake_up( sock->read_q, status );
320             if ( !(sock->state & FD_WRITE) )
321                 async_wake_up( sock->write_q, status );
322         }
323     }
324     return event;
325 }
326
327 static void sock_dispatch_events( struct sock *sock, int prevstate, int event, int error )
328 {
329     if (prevstate & FD_CONNECT)
330     {
331         sock->pmask |= FD_CONNECT;
332         sock->hmask |= FD_CONNECT;
333         sock->errors[FD_CONNECT_BIT] = error;
334         goto end;
335     }
336     if (prevstate & FD_WINE_LISTENING)
337     {
338         sock->pmask |= FD_ACCEPT;
339         sock->hmask |= FD_ACCEPT;
340         sock->errors[FD_ACCEPT_BIT] = error;
341         goto end;
342     }
343
344     if (event & POLLIN)
345     {
346         sock->pmask |= FD_READ;
347         sock->hmask |= FD_READ;
348         sock->errors[FD_READ_BIT] = 0;
349     }
350
351     if (event & POLLOUT)
352     {
353         sock->pmask |= FD_WRITE;
354         sock->hmask |= FD_WRITE;
355         sock->errors[FD_WRITE_BIT] = 0;
356     }
357
358     if (event & POLLPRI)
359     {
360         sock->pmask |= FD_OOB;
361         sock->hmask |= FD_OOB;
362         sock->errors[FD_OOB_BIT] = 0;
363     }
364
365     if (event & (POLLERR|POLLHUP))
366     {
367         sock->pmask |= FD_CLOSE;
368         sock->hmask |= FD_CLOSE;
369         sock->errors[FD_CLOSE_BIT] = error;
370     }
371 end:
372     sock_wake_up( sock );
373 }
374
375 static void sock_poll_event( struct fd *fd, int event )
376 {
377     struct sock *sock = get_fd_user( fd );
378     int hangup_seen = 0;
379     int prevstate = sock->state;
380     int error = 0;
381
382     assert( sock->obj.ops == &sock_ops );
383     if (debug_level)
384         fprintf(stderr, "socket %p select event: %x\n", sock, event);
385
386     /* we may change event later, remove from loop here */
387     if (event & (POLLERR|POLLHUP)) set_fd_events( sock->fd, -1 );
388
389     if (sock->state & FD_CONNECT)
390     {
391         if (event & (POLLERR|POLLHUP))
392         {
393             /* we didn't get connected? */
394             sock->state &= ~FD_CONNECT;
395             event &= ~POLLOUT;
396             error = sock_error( fd );
397         }
398         else if (event & POLLOUT)
399         {
400             /* we got connected */
401             sock->state |= FD_WINE_CONNECTED|FD_READ|FD_WRITE;
402             sock->state &= ~FD_CONNECT;
403         }
404     }
405     else if (sock->state & FD_WINE_LISTENING)
406     {
407         /* listening */
408         if (event & (POLLERR|POLLHUP))
409             error = sock_error( fd );
410     }
411     else
412     {
413         /* normal data flow */
414         if ( sock->type == SOCK_STREAM && ( event & POLLIN ) )
415         {
416             char dummy;
417             int nr;
418
419             /* Linux 2.4 doesn't report POLLHUP if only one side of the socket
420              * has been closed, so we need to check for it explicitly here */
421             nr  = recv( get_unix_fd( fd ), &dummy, 1, MSG_PEEK );
422             if ( nr == 0 )
423             {
424                 hangup_seen = 1;
425                 event &= ~POLLIN;
426             }
427             else if ( nr < 0 )
428             {
429                 event &= ~POLLIN;
430                 /* EAGAIN can happen if an async recv() falls between the server's poll()
431                    call and the invocation of this routine */
432                 if ( errno != EAGAIN )
433                 {
434                     error = errno;
435                     event |= POLLERR;
436                     if ( debug_level )
437                         fprintf( stderr, "recv error on socket %p: %d\n", sock, errno );
438                 }
439             }
440         }
441
442         if ( (hangup_seen || event & (POLLHUP|POLLERR)) && (sock->state & (FD_READ|FD_WRITE)) )
443         {
444             error = error ? error : sock_error( fd );
445             if ( (event & POLLERR) || ( sock_shutdown_type == SOCK_SHUTDOWN_EOF && (event & POLLHUP) ))
446                 sock->state &= ~FD_WRITE;
447             sock->state &= ~FD_READ;
448
449             if (debug_level)
450                 fprintf(stderr, "socket %p aborted by error %d, event: %x\n", sock, error, event);
451         }
452
453         if (hangup_seen)
454             event |= POLLHUP;
455     }
456
457     event = sock_dispatch_asyncs( sock, event, error );
458     sock_dispatch_events( sock, prevstate, event, error );
459
460     /* if anyone is stupid enough to wait on the socket object itself,
461      * maybe we should wake them up too, just in case? */
462     wake_up( &sock->obj, 0 );
463
464     sock_reselect( sock );
465 }
466
467 static void sock_dump( struct object *obj, int verbose )
468 {
469     struct sock *sock = (struct sock *)obj;
470     assert( obj->ops == &sock_ops );
471     printf( "Socket fd=%p, state=%x, mask=%x, pending=%x, held=%x\n",
472             sock->fd, sock->state,
473             sock->mask, sock->pmask, sock->hmask );
474 }
475
476 static int sock_signaled( struct object *obj, struct thread *thread )
477 {
478     struct sock *sock = (struct sock *)obj;
479     assert( obj->ops == &sock_ops );
480
481     return check_fd_events( sock->fd, sock_get_poll_events( sock->fd ) ) != 0;
482 }
483
484 static int sock_get_poll_events( struct fd *fd )
485 {
486     struct sock *sock = get_fd_user( fd );
487     unsigned int mask = sock->mask & ~sock->hmask;
488     unsigned int smask = sock->state & mask;
489     int ev = 0;
490
491     assert( sock->obj.ops == &sock_ops );
492
493     if (sock->state & FD_CONNECT)
494         /* connecting, wait for writable */
495         return POLLOUT;
496
497     if ( async_queued( sock->read_q ) )
498     {
499         if ( async_waiting( sock->read_q ) ) ev |= POLLIN | POLLPRI;
500     }
501     else if (smask & FD_READ || (sock->state & FD_WINE_LISTENING && mask & FD_ACCEPT))
502         ev |= POLLIN | POLLPRI;
503     /* We use POLLIN with 0 bytes recv() as FD_CLOSE indication for stream sockets. */
504     else if ( sock->type == SOCK_STREAM && sock->state & FD_READ && mask & FD_CLOSE &&
505               !(sock->hmask & FD_READ) )
506         ev |= POLLIN;
507
508     if ( async_queued( sock->write_q ) )
509     {
510         if ( async_waiting( sock->write_q ) ) ev |= POLLOUT;
511     }
512     else if (smask & FD_WRITE)
513         ev |= POLLOUT;
514
515     return ev;
516 }
517
518 static enum server_fd_type sock_get_fd_type( struct fd *fd )
519 {
520     return FD_TYPE_SOCKET;
521 }
522
523 static void sock_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
524 {
525     struct sock *sock = get_fd_user( fd );
526     struct async *async;
527     struct async_queue *queue;
528
529     assert( sock->obj.ops == &sock_ops );
530
531     switch (type)
532     {
533     case ASYNC_TYPE_READ:
534         if (!sock->read_q && !(sock->read_q = create_async_queue( sock->fd ))) return;
535         queue = sock->read_q;
536         break;
537     case ASYNC_TYPE_WRITE:
538         if (!sock->write_q && !(sock->write_q = create_async_queue( sock->fd ))) return;
539         queue = sock->write_q;
540         break;
541     default:
542         set_error( STATUS_INVALID_PARAMETER );
543         return;
544     }
545
546     if ( ( !( sock->state & (FD_READ|FD_CONNECT|FD_WINE_LISTENING) ) && type == ASYNC_TYPE_READ  ) ||
547          ( !( sock->state & (FD_WRITE|FD_CONNECT) ) && type == ASYNC_TYPE_WRITE ) )
548     {
549         set_error( STATUS_PIPE_DISCONNECTED );
550         return;
551     }
552
553     if (!(async = create_async( current, queue, data ))) return;
554     release_object( async );
555
556     sock_reselect( sock );
557
558     set_error( STATUS_PENDING );
559 }
560
561 static void sock_reselect_async( struct fd *fd, struct async_queue *queue )
562 {
563     struct sock *sock = get_fd_user( fd );
564     sock_reselect( sock );
565 }
566
567 static void sock_cancel_async( struct fd *fd, struct process *process, struct thread *thread, client_ptr_t iosb )
568 {
569     struct sock *sock = get_fd_user( fd );
570     int n = 0;
571     assert( sock->obj.ops == &sock_ops );
572
573     n += async_wake_up_by( sock->read_q, process, thread, iosb, STATUS_CANCELLED );
574     n += async_wake_up_by( sock->write_q, process, thread, iosb, STATUS_CANCELLED );
575     if (!n && iosb)
576         set_error( STATUS_NOT_FOUND );
577 }
578
579 static struct fd *sock_get_fd( struct object *obj )
580 {
581     struct sock *sock = (struct sock *)obj;
582     return (struct fd *)grab_object( sock->fd );
583 }
584
585 static void sock_destroy( struct object *obj )
586 {
587     struct sock *sock = (struct sock *)obj;
588     assert( obj->ops == &sock_ops );
589
590     /* FIXME: special socket shutdown stuff? */
591
592     if ( sock->deferred )
593         release_object( sock->deferred );
594
595     free_async_queue( sock->read_q );
596     free_async_queue( sock->write_q );
597     if (sock->event) release_object( sock->event );
598     if (sock->fd)
599     {
600         /* shut the socket down to force pending poll() calls in the client to return */
601         shutdown( get_unix_fd(sock->fd), SHUT_RDWR );
602         release_object( sock->fd );
603     }
604 }
605
606 static void init_sock(struct sock *sock)
607 {
608     sock->state = 0;
609     sock->mask    = 0;
610     sock->hmask   = 0;
611     sock->pmask   = 0;
612     sock->polling = 0;
613     sock->flags   = 0;
614     sock->type    = 0;
615     sock->family  = 0;
616     sock->event   = NULL;
617     sock->window  = 0;
618     sock->message = 0;
619     sock->wparam  = 0;
620     sock->deferred = NULL;
621     sock->read_q  = NULL;
622     sock->write_q = NULL;
623     memset( sock->errors, 0, sizeof(sock->errors) );
624 }
625
626 /* create a new and unconnected socket */
627 static struct object *create_socket( int family, int type, int protocol, unsigned int flags )
628 {
629     struct sock *sock;
630     int sockfd;
631
632     sockfd = socket( family, type, protocol );
633     if (debug_level)
634         fprintf(stderr,"socket(%d,%d,%d)=%d\n",family,type,protocol,sockfd);
635     if (sockfd == -1)
636     {
637         sock_set_error();
638         return NULL;
639     }
640     fcntl(sockfd, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
641     if (!(sock = alloc_object( &sock_ops )))
642     {
643         close( sockfd );
644         return NULL;
645     }
646     init_sock( sock );
647     sock->state  = (type != SOCK_STREAM) ? (FD_READ|FD_WRITE) : 0;
648     sock->flags  = flags;
649     sock->type   = type;
650     sock->family = family;
651
652     if (!(sock->fd = create_anonymous_fd( &sock_fd_ops, sockfd, &sock->obj,
653                             (flags & WSA_FLAG_OVERLAPPED) ? 0 : FILE_SYNCHRONOUS_IO_NONALERT )))
654     {
655         release_object( sock );
656         return NULL;
657     }
658     sock_reselect( sock );
659     clear_error();
660     return &sock->obj;
661 }
662
663 /* accepts a socket and inits it */
664 static int accept_new_fd( struct sock *sock )
665 {
666
667     /* Try to accept(2). We can't be safe that this an already connected socket
668      * or that accept() is allowed on it. In those cases we will get -1/errno
669      * return.
670      */
671     int acceptfd;
672     struct sockaddr saddr;
673     unsigned int slen = sizeof(saddr);
674     acceptfd = accept( get_unix_fd(sock->fd), &saddr, &slen);
675     if (acceptfd == -1)
676     {
677         sock_set_error();
678         return acceptfd;
679     }
680
681     fcntl(acceptfd, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
682     return acceptfd;
683 }
684
685 /* accept a socket (creates a new fd) */
686 static struct sock *accept_socket( obj_handle_t handle )
687 {
688     struct sock *acceptsock;
689     struct sock *sock;
690     int acceptfd;
691
692     sock = (struct sock *)get_handle_obj( current->process, handle, FILE_READ_DATA, &sock_ops );
693     if (!sock)
694         return NULL;
695
696     if ( sock->deferred )
697     {
698         acceptsock = sock->deferred;
699         sock->deferred = NULL;
700     }
701     else
702     {
703         if ((acceptfd = accept_new_fd( sock )) == -1)
704         {
705             release_object( sock );
706             return NULL;
707         }
708         if (!(acceptsock = alloc_object( &sock_ops )))
709         {
710             close( acceptfd );
711             release_object( sock );
712             return NULL;
713         }
714
715         init_sock( acceptsock );
716         /* newly created socket gets the same properties of the listening socket */
717         acceptsock->state  = FD_WINE_CONNECTED|FD_READ|FD_WRITE;
718         if (sock->state & FD_WINE_NONBLOCKING)
719             acceptsock->state |= FD_WINE_NONBLOCKING;
720         acceptsock->mask    = sock->mask;
721         acceptsock->type    = sock->type;
722         acceptsock->family  = sock->family;
723         acceptsock->window  = sock->window;
724         acceptsock->message = sock->message;
725         if (sock->event) acceptsock->event = (struct event *)grab_object( sock->event );
726         acceptsock->flags = sock->flags;
727         if (!(acceptsock->fd = create_anonymous_fd( &sock_fd_ops, acceptfd, &acceptsock->obj,
728                                                     get_fd_options( sock->fd ) )))
729         {
730             release_object( acceptsock );
731             release_object( sock );
732             return NULL;
733         }
734     }
735     clear_error();
736     sock->pmask &= ~FD_ACCEPT;
737     sock->hmask &= ~FD_ACCEPT;
738     sock_reselect( sock );
739     release_object( sock );
740     return acceptsock;
741 }
742
743 static int accept_into_socket( struct sock *sock, struct sock *acceptsock )
744 {
745     int acceptfd;
746     struct fd *newfd;
747     if ( sock->deferred )
748     {
749         newfd = dup_fd_object( sock->deferred->fd, 0, 0,
750                                get_fd_options( acceptsock->fd ) );
751         if ( !newfd )
752             return FALSE;
753
754         set_fd_user( newfd, &sock_fd_ops, &acceptsock->obj );
755
756         release_object( sock->deferred );
757         sock->deferred = NULL;
758     }
759     else
760     {
761         if ((acceptfd = accept_new_fd( sock )) == -1)
762             return FALSE;
763
764         if (!(newfd = create_anonymous_fd( &sock_fd_ops, acceptfd, &acceptsock->obj,
765                                             get_fd_options( acceptsock->fd ) )))
766         {
767             close( acceptfd );
768             return FALSE;
769         }
770     }
771
772     acceptsock->state  |= FD_WINE_CONNECTED|FD_READ|FD_WRITE;
773     acceptsock->hmask   = 0;
774     acceptsock->pmask   = 0;
775     acceptsock->polling = 0;
776     acceptsock->type    = sock->type;
777     acceptsock->family  = sock->family;
778     acceptsock->wparam  = 0;
779     acceptsock->deferred = NULL;
780     release_object( acceptsock->fd );
781     acceptsock->fd = newfd;
782
783     clear_error();
784     sock->pmask &= ~FD_ACCEPT;
785     sock->hmask &= ~FD_ACCEPT;
786     sock_reselect( sock );
787
788     return TRUE;
789 }
790
791 /* set the last error depending on errno */
792 static int sock_get_error( int err )
793 {
794     switch (err)
795     {
796         case EINTR:             return WSAEINTR;
797         case EBADF:             return WSAEBADF;
798         case EPERM:
799         case EACCES:            return WSAEACCES;
800         case EFAULT:            return WSAEFAULT;
801         case EINVAL:            return WSAEINVAL;
802         case EMFILE:            return WSAEMFILE;
803         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
804         case EINPROGRESS:       return WSAEINPROGRESS;
805         case EALREADY:          return WSAEALREADY;
806         case ENOTSOCK:          return WSAENOTSOCK;
807         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
808         case EMSGSIZE:          return WSAEMSGSIZE;
809         case EPROTOTYPE:        return WSAEPROTOTYPE;
810         case ENOPROTOOPT:       return WSAENOPROTOOPT;
811         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
812         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
813         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
814         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
815         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
816         case EADDRINUSE:        return WSAEADDRINUSE;
817         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
818         case ENETDOWN:          return WSAENETDOWN;
819         case ENETUNREACH:       return WSAENETUNREACH;
820         case ENETRESET:         return WSAENETRESET;
821         case ECONNABORTED:      return WSAECONNABORTED;
822         case EPIPE:
823         case ECONNRESET:        return WSAECONNRESET;
824         case ENOBUFS:           return WSAENOBUFS;
825         case EISCONN:           return WSAEISCONN;
826         case ENOTCONN:          return WSAENOTCONN;
827         case ESHUTDOWN:         return WSAESHUTDOWN;
828         case ETOOMANYREFS:      return WSAETOOMANYREFS;
829         case ETIMEDOUT:         return WSAETIMEDOUT;
830         case ECONNREFUSED:      return WSAECONNREFUSED;
831         case ELOOP:             return WSAELOOP;
832         case ENAMETOOLONG:      return WSAENAMETOOLONG;
833         case EHOSTDOWN:         return WSAEHOSTDOWN;
834         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
835         case ENOTEMPTY:         return WSAENOTEMPTY;
836 #ifdef EPROCLIM
837         case EPROCLIM:          return WSAEPROCLIM;
838 #endif
839 #ifdef EUSERS
840         case EUSERS:            return WSAEUSERS;
841 #endif
842 #ifdef EDQUOT
843         case EDQUOT:            return WSAEDQUOT;
844 #endif
845 #ifdef ESTALE
846         case ESTALE:            return WSAESTALE;
847 #endif
848 #ifdef EREMOTE
849         case EREMOTE:           return WSAEREMOTE;
850 #endif
851
852         case 0:                 return 0;
853         default:
854             errno = err;
855             perror("wineserver: sock_get_error() can't map error");
856             return WSAEFAULT;
857     }
858 }
859
860 static int sock_get_ntstatus( int err )
861 {
862     switch ( err )
863     {
864         case EBADF:             return STATUS_INVALID_HANDLE;
865         case EBUSY:             return STATUS_DEVICE_BUSY;
866         case EPERM:
867         case EACCES:            return STATUS_ACCESS_DENIED;
868         case EFAULT:            return STATUS_NO_MEMORY;
869         case EINVAL:            return STATUS_INVALID_PARAMETER;
870         case ENFILE:
871         case EMFILE:            return STATUS_TOO_MANY_OPENED_FILES;
872         case EWOULDBLOCK:       return STATUS_CANT_WAIT;
873         case EINPROGRESS:       return STATUS_PENDING;
874         case EALREADY:          return STATUS_NETWORK_BUSY;
875         case ENOTSOCK:          return STATUS_OBJECT_TYPE_MISMATCH;
876         case EDESTADDRREQ:      return STATUS_INVALID_PARAMETER;
877         case EMSGSIZE:          return STATUS_BUFFER_OVERFLOW;
878         case EPROTONOSUPPORT:
879         case ESOCKTNOSUPPORT:
880         case EPFNOSUPPORT:
881         case EAFNOSUPPORT:
882         case EPROTOTYPE:        return STATUS_NOT_SUPPORTED;
883         case ENOPROTOOPT:       return STATUS_INVALID_PARAMETER;
884         case EOPNOTSUPP:        return STATUS_NOT_SUPPORTED;
885         case EADDRINUSE:        return STATUS_ADDRESS_ALREADY_ASSOCIATED;
886         case EADDRNOTAVAIL:     return STATUS_INVALID_PARAMETER;
887         case ECONNREFUSED:      return STATUS_CONNECTION_REFUSED;
888         case ESHUTDOWN:         return STATUS_PIPE_DISCONNECTED;
889         case ENOTCONN:          return STATUS_CONNECTION_DISCONNECTED;
890         case ETIMEDOUT:         return STATUS_IO_TIMEOUT;
891         case ENETUNREACH:       return STATUS_NETWORK_UNREACHABLE;
892         case EHOSTUNREACH:      return STATUS_HOST_UNREACHABLE;
893         case ENETDOWN:          return STATUS_NETWORK_BUSY;
894         case EPIPE:
895         case ECONNRESET:        return STATUS_CONNECTION_RESET;
896         case ECONNABORTED:      return STATUS_CONNECTION_ABORTED;
897
898         case 0:                 return STATUS_SUCCESS;
899         default:
900             errno = err;
901             perror("wineserver: sock_get_ntstatus() can't map error");
902             return STATUS_UNSUCCESSFUL;
903     }
904 }
905
906 /* set the last error depending on errno */
907 static void sock_set_error(void)
908 {
909     set_error( sock_get_ntstatus( errno ) );
910 }
911
912 /* create a socket */
913 DECL_HANDLER(create_socket)
914 {
915     struct object *obj;
916
917     reply->handle = 0;
918     if ((obj = create_socket( req->family, req->type, req->protocol, req->flags )) != NULL)
919     {
920         reply->handle = alloc_handle( current->process, obj, req->access, req->attributes );
921         release_object( obj );
922     }
923 }
924
925 /* accept a socket */
926 DECL_HANDLER(accept_socket)
927 {
928     struct sock *sock;
929
930     reply->handle = 0;
931     if ((sock = accept_socket( req->lhandle )) != NULL)
932     {
933         reply->handle = alloc_handle( current->process, &sock->obj, req->access, req->attributes );
934         sock->wparam = reply->handle;  /* wparam for message is the socket handle */
935         sock_reselect( sock );
936         release_object( &sock->obj );
937     }
938 }
939
940 /* accept a socket into an initialized socket */
941 DECL_HANDLER(accept_into_socket)
942 {
943     struct sock *sock, *acceptsock;
944     const int all_attributes = FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES|FILE_READ_DATA;
945
946     if (!(sock = (struct sock *)get_handle_obj( current->process, req->lhandle,
947                                                 all_attributes, &sock_ops)))
948         return;
949
950     if (!(acceptsock = (struct sock *)get_handle_obj( current->process, req->ahandle,
951                                                       all_attributes, &sock_ops)))
952     {
953         release_object( sock );
954         return;
955     }
956
957     if (accept_into_socket( sock, acceptsock ))
958     {
959         acceptsock->wparam = req->ahandle;  /* wparam for message is the socket handle */
960         sock_reselect( acceptsock );
961     }
962     release_object( acceptsock );
963     release_object( sock );
964 }
965
966 /* set socket event parameters */
967 DECL_HANDLER(set_socket_event)
968 {
969     struct sock *sock;
970     struct event *old_event;
971
972     if (!(sock = (struct sock *)get_handle_obj( current->process, req->handle,
973                                                 FILE_WRITE_ATTRIBUTES, &sock_ops))) return;
974     old_event = sock->event;
975     sock->mask    = req->mask;
976     sock->hmask   &= ~req->mask; /* re-enable held events */
977     sock->event   = NULL;
978     sock->window  = req->window;
979     sock->message = req->msg;
980     sock->wparam  = req->handle;  /* wparam is the socket handle */
981     if (req->event) sock->event = get_event_obj( current->process, req->event, EVENT_MODIFY_STATE );
982
983     if (debug_level && sock->event) fprintf(stderr, "event ptr: %p\n", sock->event);
984
985     sock_reselect( sock );
986
987     if (sock->mask)
988         sock->state |= FD_WINE_NONBLOCKING;
989
990     /* if a network event is pending, signal the event object
991        it is possible that FD_CONNECT or FD_ACCEPT network events has happened
992        before a WSAEventSelect() was done on it.
993        (when dealing with Asynchronous socket)  */
994     sock_wake_up( sock );
995
996     if (old_event) release_object( old_event ); /* we're through with it */
997     release_object( &sock->obj );
998 }
999
1000 /* get socket event parameters */
1001 DECL_HANDLER(get_socket_event)
1002 {
1003     struct sock *sock;
1004     int i;
1005     int errors[FD_MAX_EVENTS];
1006
1007     sock = (struct sock *)get_handle_obj( current->process, req->handle, FILE_READ_ATTRIBUTES, &sock_ops );
1008     if (!sock)
1009     {
1010         reply->mask  = 0;
1011         reply->pmask = 0;
1012         reply->state = 0;
1013         return;
1014     }
1015     reply->mask  = sock->mask;
1016     reply->pmask = sock->pmask;
1017     reply->state = sock->state;
1018     for (i = 0; i < FD_MAX_EVENTS; i++)
1019         errors[i] = sock_get_ntstatus(sock->errors[i]);
1020
1021     set_reply_data( errors, min( get_reply_max_size(), sizeof(errors) ));
1022
1023     if (req->service)
1024     {
1025         if (req->c_event)
1026         {
1027             struct event *cevent = get_event_obj( current->process, req->c_event,
1028                                                   EVENT_MODIFY_STATE );
1029             if (cevent)
1030             {
1031                 reset_event( cevent );
1032                 release_object( cevent );
1033             }
1034         }
1035         sock->pmask = 0;
1036         sock_reselect( sock );
1037     }
1038     release_object( &sock->obj );
1039 }
1040
1041 /* re-enable pending socket events */
1042 DECL_HANDLER(enable_socket_event)
1043 {
1044     struct sock *sock;
1045
1046     if (!(sock = (struct sock*)get_handle_obj( current->process, req->handle,
1047                                                FILE_WRITE_ATTRIBUTES, &sock_ops)))
1048         return;
1049
1050     /* for event-based notification, windows erases stale events */
1051     sock->pmask &= ~req->mask;
1052
1053     sock->hmask &= ~req->mask;
1054     sock->state |= req->sstate;
1055     sock->state &= ~req->cstate;
1056     if ( sock->type != SOCK_STREAM ) sock->state &= ~STREAM_FLAG_MASK;
1057
1058     sock_reselect( sock );
1059
1060     release_object( &sock->obj );
1061 }
1062
1063 DECL_HANDLER(set_socket_deferred)
1064 {
1065     struct sock *sock, *acceptsock;
1066
1067     sock=(struct sock *)get_handle_obj( current->process, req->handle, FILE_WRITE_ATTRIBUTES, &sock_ops );
1068     if ( !sock )
1069         return;
1070
1071     acceptsock = (struct sock *)get_handle_obj( current->process, req->deferred, 0, &sock_ops );
1072     if ( !acceptsock )
1073     {
1074         release_object( sock );
1075         return;
1076     }
1077     sock->deferred = acceptsock;
1078     release_object( sock );
1079 }