sock.c 28.8 KB
Newer Older
1 2 3 4 5
/*
 * Server-side socket management
 *
 * Copyright (C) 1999 Marcus Meissner, Ove Kven
 *
6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
20 21 22 23
 * FIXME: we use read|write access in all cases. Shouldn't we depend that
 * on the access of the current handle?
 */

24 25
#include "config.h"

26 27
#include <assert.h>
#include <fcntl.h>
28
#include <stdarg.h>
29 30 31 32
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
33 34 35
#ifdef HAVE_SYS_ERRNO_H
# include <sys/errno.h>
#endif
36 37
#include <sys/time.h>
#include <sys/types.h>
38 39 40
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
Steven Edwards's avatar
Steven Edwards committed
41
#ifdef HAVE_SYS_IOCTL_H
42
#include <sys/ioctl.h>
Steven Edwards's avatar
Steven Edwards committed
43
#endif
44 45 46
#ifdef HAVE_SYS_FILIO_H
# include <sys/filio.h>
#endif
47 48 49
#include <time.h>
#include <unistd.h>

50
#include "windef.h"
51
#include "winbase.h"
52

53
#include "process.h"
54
#include "file.h"
55 56 57
#include "handle.h"
#include "thread.h"
#include "request.h"
58
#include "user.h"
59

60 61 62 63 64 65
/* To avoid conflicts with the Unix socket headers. Plus we only need a few
 * macros anyway.
 */
#define USE_WS_PREFIX
#include "winsock2.h"

66 67 68
struct sock
{
    struct object       obj;         /* object header */
69
    struct fd          *fd;          /* socket file descriptor */
70 71 72 73
    unsigned int        state;       /* status bits */
    unsigned int        mask;        /* event mask */
    unsigned int        hmask;       /* held (blocked) events */
    unsigned int        pmask;       /* pending events */
74
    unsigned int        flags;       /* socket flags */
75
    int                 polling;     /* is socket being polled? */
76 77
    unsigned short      type;        /* socket type */
    unsigned short      family;      /* socket family */
78
    struct event       *event;       /* event object */
79 80
    user_handle_t       window;      /* window to send the message to */
    unsigned int        message;     /* message to send */
81
    obj_handle_t        wparam;      /* message wparam (socket handle) */
82
    int                 errors[FD_MAX_EVENTS]; /* event errors */
83
    struct sock        *deferred;    /* socket that waits for a deferred accept */
84 85
    struct list         read_q;      /* queue for asynchronous reads */
    struct list         write_q;     /* queue for asynchronous writes */
86 87 88 89
};

static void sock_dump( struct object *obj, int verbose );
static int sock_signaled( struct object *obj, struct thread *thread );
90
static struct fd *sock_get_fd( struct object *obj );
91
static void sock_destroy( struct object *obj );
92 93 94

static int sock_get_poll_events( struct fd *fd );
static void sock_poll_event( struct fd *fd, int event );
95
static int sock_get_info( struct fd *fd );
96 97
static void sock_queue_async( struct fd *fd, void *apc, void *user, void *iosb, int type, int count );
static void sock_cancel_async( struct fd *fd );
98

99
static int sock_get_error( int err );
100 101 102 103
static void sock_set_error(void);

static const struct object_ops sock_ops =
{
104 105 106 107 108 109
    sizeof(struct sock),          /* size */
    sock_dump,                    /* dump */
    add_queue,                    /* add_queue */
    remove_queue,                 /* remove_queue */
    sock_signaled,                /* signaled */
    no_satisfied,                 /* satisfied */
110
    no_signal,                    /* signal */
111
    sock_get_fd,                  /* get_fd */
112 113 114 115 116
    sock_destroy                  /* destroy */
};

static const struct fd_ops sock_fd_ops =
{
117 118 119
    sock_get_poll_events,         /* get_poll_events */
    sock_poll_event,              /* poll_event */
    no_flush,                     /* flush */
120
    sock_get_info,                /* get_file_info */
121 122
    sock_queue_async,             /* queue_async */
    sock_cancel_async             /* cancel_async */
123 124
};

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

/* Permutation of 0..FD_MAX_EVENTS - 1 representing the order in which
 * we post messages if there are multiple events.  Used to send
 * messages.  The problem is if there is both a FD_CONNECT event and,
 * say, an FD_READ event available on the same socket, we want to
 * notify the app of the connect event first.  Otherwise it may
 * discard the read event because it thinks it hasn't connected yet.
 */
static const int event_bitorder[FD_MAX_EVENTS] =
{
    FD_CONNECT_BIT,
    FD_ACCEPT_BIT,
    FD_OOB_BIT,
    FD_WRITE_BIT,
    FD_READ_BIT,
    FD_CLOSE_BIT,
    6, 7, 8, 9  /* leftovers */
};

144 145 146 147 148 149 150 151 152 153 154
/* Flags that make sense only for SOCK_STREAM sockets */
#define STREAM_FLAG_MASK ((unsigned int) (FD_CONNECT | FD_ACCEPT | FD_WINE_LISTENING | FD_WINE_CONNECTED))

typedef enum {
    SOCK_SHUTDOWN_ERROR = -1,
    SOCK_SHUTDOWN_EOF = 0,
    SOCK_SHUTDOWN_POLLHUP = 1
} sock_shutdown_t;

static sock_shutdown_t sock_shutdown_type = SOCK_SHUTDOWN_ERROR;

155
static sock_shutdown_t sock_check_pollhup(void)
156 157 158 159 160 161
{
    sock_shutdown_t ret = SOCK_SHUTDOWN_ERROR;
    int fd[2], n;
    struct pollfd pfd;
    char dummy;

162 163
    if ( socketpair( AF_UNIX, SOCK_STREAM, 0, fd ) ) goto out;
    if ( shutdown( fd[0], 1 ) ) goto out;
164 165 166 167 168

    pfd.fd = fd[1];
    pfd.events = POLLIN;
    pfd.revents = 0;

169
    n = poll( &pfd, 1, 0 );
170 171 172 173
    if ( n != 1 ) goto out; /* error or timeout */
    if ( pfd.revents & POLLHUP )
        ret = SOCK_SHUTDOWN_POLLHUP;
    else if ( pfd.revents & POLLIN &&
174
              read( fd[1], &dummy, 1 ) == 0 )
175 176 177
        ret = SOCK_SHUTDOWN_EOF;

out:
178 179
    close( fd[0] );
    close( fd[1] );
180 181 182 183 184
    return ret;
}

void sock_init(void)
{
185
    sock_shutdown_type = sock_check_pollhup();
186 187 188 189

    switch ( sock_shutdown_type )
    {
    case SOCK_SHUTDOWN_EOF:
190
        if (debug_level) fprintf( stderr, "sock_init: shutdown() causes EOF\n" );
191 192
        break;
    case SOCK_SHUTDOWN_POLLHUP:
193
        if (debug_level) fprintf( stderr, "sock_init: shutdown() causes POLLHUP\n" );
194 195
        break;
    default:
196
        fprintf( stderr, "sock_init: ERROR in sock_check_pollhup()\n" );
197 198 199
        sock_shutdown_type = SOCK_SHUTDOWN_EOF;
    }
}
200

201
static int sock_reselect( struct sock *sock )
202
{
203
    int ev = sock_get_poll_events( sock->fd );
204

205
    if (debug_level)
206
        fprintf(stderr,"sock_reselect(%p): new mask %x\n", sock, ev);
207

208 209
    if (!sock->polling)  /* FIXME: should find a better way to do this */
    {
210
        /* previously unconnected socket, is this reselect supposed to connect it? */
211
        if (!(sock->state & ~FD_WINE_NONBLOCKING)) return 0;
212
        /* ok, it is, attach it to the wineserver's main poll loop */
213
        sock->polling = 1;
214 215
    }
    /* update condition mask */
216
    set_fd_events( sock->fd, ev );
217 218 219 220 221
    return ev;
}

/* After POLLHUP is received, the socket will no longer be in the main select loop.
   This function is used to signal pending events nevertheless */
222
static void sock_try_event( struct sock *sock, int event )
223
{
224
    event = check_fd_events( sock->fd, event );
225
    if (event)
226
    {
227 228
        if ( debug_level ) fprintf( stderr, "sock_try_event: %x\n", event );
        sock_poll_event( sock->fd, event );
229
    }
230
}
231

232
/* wake anybody waiting on the socket event or send the associated message */
233
static void sock_wake_up( struct sock *sock, int pollev )
234 235 236
{
    unsigned int events = sock->pmask & sock->mask;
    int i;
237
    int async_active = 0;
238

239
    if ( sock->flags & WSA_FLAG_OVERLAPPED )
240
    {
241
        if ( pollev & (POLLIN|POLLPRI) && !list_empty( &sock->read_q ))
242
        {
243
            if (debug_level) fprintf( stderr, "activating read queue for socket %p\n", sock );
244
            async_terminate_head( &sock->read_q, STATUS_ALERTED );
245 246
            async_active = 1;
        }
247
        if ( pollev & POLLOUT && !list_empty( &sock->write_q ))
248
        {
249
            if (debug_level) fprintf( stderr, "activating write queue for socket %p\n", sock );
250
            async_terminate_head( &sock->write_q, STATUS_ALERTED );
251 252 253 254 255 256 257 258
            async_active = 1;
        }
    }

    /* Do not signal events if there are still pending asynchronous IO requests */
    /* We need this to delay FD_CLOSE events until all pending overlapped requests are processed */
    if ( !events || async_active ) return;

259 260 261 262 263 264 265
    if (sock->event)
    {
        if (debug_level) fprintf(stderr, "signalling events %x ptr %p\n", events, sock->event );
        set_event( sock->event );
    }
    if (sock->window)
    {
266
        if (debug_level) fprintf(stderr, "signalling events %x win %p\n", events, sock->window );
267 268 269 270 271 272
        for (i = 0; i < FD_MAX_EVENTS; i++)
        {
            int event = event_bitorder[i];
            if (sock->pmask & (1 << event))
            {
                unsigned int lparam = (1 << event) | (sock->errors[event] << 16);
273
                post_message( sock->window, sock->message, (unsigned int)sock->wparam, lparam );
274 275 276 277 278
            }
        }
        sock->pmask = 0;
        sock_reselect( sock );
    }
279 280
}

281
inline static int sock_error( struct fd *fd )
282
{
283
    unsigned int optval = 0, optlen;
284

285
    optlen = sizeof(optval);
286
    getsockopt( get_unix_fd(fd), SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
287
    return optval ? sock_get_error(optval) : 0;
288 289
}

290
static void sock_poll_event( struct fd *fd, int event )
291
{
292
    struct sock *sock = get_fd_user( fd );
293
    int hangup_seen = 0;
294

295
    assert( sock->obj.ops == &sock_ops );
296
    if (debug_level)
297
        fprintf(stderr, "socket %p select event: %x\n", sock, event);
298
    if (sock->state & FD_CONNECT)
299 300
    {
        /* connecting */
301
        if (event & POLLOUT)
302 303
        {
            /* we got connected */
304 305
            sock->state |= FD_WINE_CONNECTED|FD_READ|FD_WRITE;
            sock->state &= ~FD_CONNECT;
306 307
            sock->pmask |= FD_CONNECT;
            sock->errors[FD_CONNECT_BIT] = 0;
308
            if (debug_level)
309
                fprintf(stderr, "socket %p connection success\n", sock);
310
        }
311
        else if (event & (POLLERR|POLLHUP))
312 313
        {
            /* we didn't get connected? */
314
            sock->state &= ~FD_CONNECT;
315
            sock->pmask |= FD_CONNECT;
316
            sock->errors[FD_CONNECT_BIT] = sock_error( fd );
317
            if (debug_level)
318
                fprintf(stderr, "socket %p connection failure\n", sock);
319
        }
320 321
    }
    else if (sock->state & FD_WINE_LISTENING)
322 323
    {
        /* listening */
324
        if (event & POLLIN)
325 326 327 328 329 330
        {
            /* incoming connection */
            sock->pmask |= FD_ACCEPT;
            sock->errors[FD_ACCEPT_BIT] = 0;
            sock->hmask |= FD_ACCEPT;
        }
331
        else if (event & (POLLERR|POLLHUP))
332 333 334
        {
            /* failed incoming connection? */
            sock->pmask |= FD_ACCEPT;
335
            sock->errors[FD_ACCEPT_BIT] = sock_error( fd );
336 337
            sock->hmask |= FD_ACCEPT;
        }
338 339
    }
    else
340 341
    {
        /* normal data flow */
342
        if ( sock->type == SOCK_STREAM && ( event & POLLIN ) )
343
        {
344
            char dummy;
345
            int nr;
346 347 348

            /* Linux 2.4 doesn't report POLLHUP if only one side of the socket
             * has been closed, so we need to check for it explicitly here */
349
            nr  = recv( get_unix_fd( fd ), &dummy, 1, MSG_PEEK );
350
            if ( nr > 0 )
351 352 353
            {
                /* incoming data */
                sock->pmask |= FD_READ;
354
                sock->hmask |= (FD_READ|FD_CLOSE);
355 356
                sock->errors[FD_READ_BIT] = 0;
                if (debug_level)
357
                    fprintf(stderr, "socket %p is readable\n", sock );
358
            }
359
            else if ( nr == 0 )
360
                hangup_seen = 1;
361 362 363 364 365 366 367 368 369
            else
            {
                /* EAGAIN can happen if an async recv() falls between the server's poll()
                   call and the invocation of this routine */
                if ( errno == EAGAIN )
                    event &= ~POLLIN;
                else
                {
                    if ( debug_level )
370
                        fprintf( stderr, "recv error on socket %p: %d\n", sock, errno );
371 372 373 374
                    event = POLLERR;
                }
            }

375
        }
376 377 378 379 380 381 382 383 384 385
        else if ( sock_shutdown_type == SOCK_SHUTDOWN_POLLHUP && (event & POLLHUP) )
        {
            hangup_seen = 1;
        }
        else if ( event & POLLIN ) /* POLLIN for non-stream socket */
        {
            sock->pmask |= FD_READ;
            sock->hmask |= (FD_READ|FD_CLOSE);
            sock->errors[FD_READ_BIT] = 0;
            if (debug_level)
386
                fprintf(stderr, "socket %p is readable\n", sock );
387 388

        }
389

390
        if (event & POLLOUT)
391 392 393 394
        {
            sock->pmask |= FD_WRITE;
            sock->hmask |= FD_WRITE;
            sock->errors[FD_WRITE_BIT] = 0;
395
            if (debug_level)
396
                fprintf(stderr, "socket %p is writable\n", sock);
397 398 399 400 401
        }
        if (event & POLLPRI)
        {
            sock->pmask |= FD_OOB;
            sock->hmask |= FD_OOB;
402
            sock->errors[FD_OOB_BIT] = 0;
403
            if (debug_level)
404
                fprintf(stderr, "socket %p got OOB data\n", sock);
405
        }
406
        /* According to WS2 specs, FD_CLOSE is only delivered when there is
407 408
           no more data to be read (i.e. hangup_seen = 1) */
        else if ( hangup_seen && (sock->state & (FD_READ|FD_WRITE) ))
409
        {
410
            sock->errors[FD_CLOSE_BIT] = sock_error( fd );
411
            if ( (event & POLLERR) || ( sock_shutdown_type == SOCK_SHUTDOWN_EOF && (event & POLLHUP) ))
412
                sock->state &= ~FD_WRITE;
413
            sock->pmask |= FD_CLOSE;
414
            sock->hmask |= FD_CLOSE;
415
            if (debug_level)
416 417
                fprintf(stderr, "socket %p aborted by error %d, event: %x - removing from select loop\n",
                        sock, sock->errors[FD_CLOSE_BIT], event);
418 419 420
        }
    }

421 422 423
    if ( sock->pmask & FD_CLOSE || event & (POLLERR|POLLHUP) )
    {
        if ( debug_level )
424
            fprintf( stderr, "removing socket %p from select loop\n", sock );
425
        set_fd_events( sock->fd, -1 );
426 427 428
    }
    else
        sock_reselect( sock );
429

430
    /* wake up anyone waiting for whatever just happened */
431
    if ( sock->pmask & sock->mask || sock->flags & WSA_FLAG_OVERLAPPED ) sock_wake_up( sock, event );
432 433 434 435 436 437 438 439 440 441

    /* if anyone is stupid enough to wait on the socket object itself,
     * maybe we should wake them up too, just in case? */
    wake_up( &sock->obj, 0 );
}

static void sock_dump( struct object *obj, int verbose )
{
    struct sock *sock = (struct sock *)obj;
    assert( obj->ops == &sock_ops );
442
    printf( "Socket fd=%p, state=%x, mask=%x, pending=%x, held=%x\n",
443
            sock->fd, sock->state,
444
            sock->mask, sock->pmask, sock->hmask );
445 446
}

447
static int sock_signaled( struct object *obj, struct thread *thread )
448
{
449
    struct sock *sock = (struct sock *)obj;
450 451
    assert( obj->ops == &sock_ops );

452
    return check_fd_events( sock->fd, sock_get_poll_events( sock->fd ) ) != 0;
453 454
}

455
static int sock_get_poll_events( struct fd *fd )
456
{
457
    struct sock *sock = get_fd_user( fd );
458 459 460
    unsigned int mask = sock->mask & sock->state & ~sock->hmask;
    int ev = 0;

461
    assert( sock->obj.ops == &sock_ops );
462

463
    if (sock->state & FD_CONNECT)
464 465
        /* connecting, wait for writable */
        return POLLOUT;
466
    if (sock->state & FD_WINE_LISTENING)
467 468 469
        /* listening, wait for readable */
        return (sock->hmask & FD_ACCEPT) ? 0 : POLLIN;

470
    if (mask & (FD_READ) || (sock->flags & WSA_FLAG_OVERLAPPED && !list_empty( &sock->read_q )))
471
        ev |= POLLIN | POLLPRI;
472
    if (mask & FD_WRITE || (sock->flags & WSA_FLAG_OVERLAPPED && !list_empty( &sock->write_q )))
473
        ev |= POLLOUT;
474 475
    /* We use POLLIN with 0 bytes recv() as FD_CLOSE indication for stream sockets. */
    if ( sock->type == SOCK_STREAM && ( sock->mask & ~sock->hmask & FD_CLOSE) )
476 477
        ev |= POLLIN;

478
    return ev;
479 480
}

481
static int sock_get_info( struct fd *fd )
482
{
483
    int flags = FD_FLAG_AVAILABLE;
484
    struct sock *sock = get_fd_user( fd );
485
    assert( sock->obj.ops == &sock_ops );
486

487
    if (sock->flags & WSA_FLAG_OVERLAPPED) flags |= FD_FLAG_OVERLAPPED;
488 489
    if ( sock->type != SOCK_STREAM || sock->state & FD_WINE_CONNECTED )
    {
490 491
        if ( !(sock->state & FD_READ  ) ) flags |= FD_FLAG_RECV_SHUTDOWN;
        if ( !(sock->state & FD_WRITE ) ) flags |= FD_FLAG_SEND_SHUTDOWN;
492
    }
493
    return flags;
494 495
}

496 497
static void sock_queue_async( struct fd *fd, void *apc, void *user, void *iosb,
                              int type, int count )
498
{
499
    struct sock *sock = get_fd_user( fd );
500
    struct list *queue;
501
    int pollev;
502

503
    assert( sock->obj.ops == &sock_ops );
504 505 506

    if ( !(sock->flags & WSA_FLAG_OVERLAPPED) )
    {
507
        set_error( STATUS_INVALID_HANDLE );
508 509 510
        return;
    }

511
    switch (type)
512 513
    {
    case ASYNC_TYPE_READ:
514
        queue = &sock->read_q;
515
        sock->hmask &= ~FD_CLOSE;
516 517
        break;
    case ASYNC_TYPE_WRITE:
518
        queue = &sock->write_q;
519 520 521 522 523 524
        break;
    default:
        set_error( STATUS_INVALID_PARAMETER );
        return;
    }

525 526
    if ( ( !( sock->state & FD_READ ) && type == ASYNC_TYPE_READ  ) ||
         ( !( sock->state & FD_WRITE ) && type == ASYNC_TYPE_WRITE ) )
527
    {
528 529 530 531
        set_error( STATUS_PIPE_DISCONNECTED );
    }
    else
    {
532
        if (!create_async( current, NULL, queue, apc, user, iosb ))
533
            return;
534 535
    }

536 537 538 539 540 541 542 543 544 545 546
    pollev = sock_reselect( sock );
    if ( pollev ) sock_try_event( sock, pollev );
}

static void sock_cancel_async( struct fd *fd )
{
    struct sock *sock = get_fd_user( fd );
    assert( sock->obj.ops == &sock_ops );

    async_terminate_queue( &sock->read_q, STATUS_CANCELLED );
    async_terminate_queue( &sock->write_q, STATUS_CANCELLED );
547 548
}

549 550 551 552 553 554
static struct fd *sock_get_fd( struct object *obj )
{
    struct sock *sock = (struct sock *)obj;
    return (struct fd *)grab_object( sock->fd );
}

555 556 557 558 559 560
static void sock_destroy( struct object *obj )
{
    struct sock *sock = (struct sock *)obj;
    assert( obj->ops == &sock_ops );

    /* FIXME: special socket shutdown stuff? */
561

562
    if ( sock->deferred )
563
        release_object( sock->deferred );
564

565 566
    if ( sock->flags & WSA_FLAG_OVERLAPPED )
    {
567 568
        async_terminate_queue( &sock->read_q, STATUS_CANCELLED );
        async_terminate_queue( &sock->write_q, STATUS_CANCELLED );
569
    }
570
    if (sock->event) release_object( sock->event );
571
    if (sock->fd) release_object( sock->fd );
572 573 574
}

/* create a new and unconnected socket */
575
static struct object *create_socket( int family, int type, int protocol, unsigned int flags )
576 577
{
    struct sock *sock;
578
    int sockfd;
579

580 581 582
    sockfd = socket( family, type, protocol );
    if (debug_level)
        fprintf(stderr,"socket(%d,%d,%d)=%d\n",family,type,protocol,sockfd);
583 584
    if (sockfd == -1)
    {
585 586 587 588
        sock_set_error();
        return NULL;
    }
    fcntl(sockfd, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
589 590 591 592 593
    if (!(sock = alloc_object( &sock_ops )))
    {
        close( sockfd );
        return NULL;
    }
594
    sock->state = (type != SOCK_STREAM) ? (FD_READ|FD_WRITE) : 0;
595 596 597
    sock->mask    = 0;
    sock->hmask   = 0;
    sock->pmask   = 0;
598
    sock->polling = 0;
599
    sock->flags   = flags;
600 601
    sock->type    = type;
    sock->family  = family;
602 603 604 605
    sock->event   = NULL;
    sock->window  = 0;
    sock->message = 0;
    sock->wparam  = 0;
606
    sock->deferred = NULL;
607
    if (!(sock->fd = create_anonymous_fd( &sock_fd_ops, sockfd, &sock->obj )))
608 609 610 611
    {
        release_object( sock );
        return NULL;
    }
612 613
    list_init( &sock->read_q );
    list_init( &sock->write_q );
614 615
    sock_reselect( sock );
    clear_error();
616 617 618 619
    return &sock->obj;
}

/* accept a socket (creates a new fd) */
620
static struct sock *accept_socket( obj_handle_t handle )
621 622 623 624 625 626 627 628 629 630 631 632
{
    struct sock *acceptsock;
    struct sock *sock;
    int	acceptfd;
    struct sockaddr	saddr;
    int			slen;

    sock=(struct sock*)get_handle_obj(current->process,handle,
                                      GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,&sock_ops);
    if (!sock)
    	return NULL;

633 634
    if ( sock->deferred )
    {
635 636
        acceptsock = sock->deferred;
        sock->deferred = NULL;
637 638 639
    }
    else
    {
640 641 642 643 644 645

        /* Try to accept(2). We can't be safe that this an already connected socket
         * or that accept() is allowed on it. In those cases we will get -1/errno
         * return.
         */
        slen = sizeof(saddr);
646
        acceptfd = accept( get_unix_fd(sock->fd), &saddr, &slen);
647 648
        if (acceptfd==-1)
        {
649 650 651 652
            sock_set_error();
            release_object( sock );
            return NULL;
        }
653
        if (!(acceptsock = alloc_object( &sock_ops )))
654
        {
655
            close( acceptfd );
656 657 658
            release_object( sock );
            return NULL;
        }
659

660 661 662 663 664 665 666 667
        /* newly created socket gets the same properties of the listening socket */
        fcntl(acceptfd, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
        acceptsock->state  = FD_WINE_CONNECTED|FD_READ|FD_WRITE;
        if (sock->state & FD_WINE_NONBLOCKING)
            acceptsock->state |= FD_WINE_NONBLOCKING;
        acceptsock->mask    = sock->mask;
        acceptsock->hmask   = 0;
        acceptsock->pmask   = 0;
668
        acceptsock->polling = 0;
669 670
        acceptsock->type    = sock->type;
        acceptsock->family  = sock->family;
671 672 673 674 675 676
        acceptsock->event   = NULL;
        acceptsock->window  = sock->window;
        acceptsock->message = sock->message;
        acceptsock->wparam  = 0;
        if (sock->event) acceptsock->event = (struct event *)grab_object( sock->event );
        acceptsock->flags = sock->flags;
677
        acceptsock->deferred = NULL;
678
        if (!(acceptsock->fd = create_anonymous_fd( &sock_fd_ops, acceptfd, &acceptsock->obj )))
679 680 681 682 683
        {
            release_object( acceptsock );
            release_object( sock );
            return NULL;
        }
684 685
        list_init( &acceptsock->read_q );
        list_init( &acceptsock->write_q );
686
    }
687 688 689
    clear_error();
    sock->pmask &= ~FD_ACCEPT;
    sock->hmask &= ~FD_ACCEPT;
690
    sock_reselect( sock );
691
    release_object( sock );
692
    return acceptsock;
693 694 695
}

/* set the last error depending on errno */
696
static int sock_get_error( int err )
697
{
698
    switch (err)
699
    {
700 701
        case EINTR:             return WSAEINTR;
        case EBADF:             return WSAEBADF;
702
        case EPERM:
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
        case EACCES:            return WSAEACCES;
        case EFAULT:            return WSAEFAULT;
        case EINVAL:            return WSAEINVAL;
        case EMFILE:            return WSAEMFILE;
        case EWOULDBLOCK:       return WSAEWOULDBLOCK;
        case EINPROGRESS:       return WSAEINPROGRESS;
        case EALREADY:          return WSAEALREADY;
        case ENOTSOCK:          return WSAENOTSOCK;
        case EDESTADDRREQ:      return WSAEDESTADDRREQ;
        case EMSGSIZE:          return WSAEMSGSIZE;
        case EPROTOTYPE:        return WSAEPROTOTYPE;
        case ENOPROTOOPT:       return WSAENOPROTOOPT;
        case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
        case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
        case EOPNOTSUPP:        return WSAEOPNOTSUPP;
        case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
        case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
        case EADDRINUSE:        return WSAEADDRINUSE;
        case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
        case ENETDOWN:          return WSAENETDOWN;
        case ENETUNREACH:       return WSAENETUNREACH;
        case ENETRESET:         return WSAENETRESET;
        case ECONNABORTED:      return WSAECONNABORTED;
726
        case EPIPE:
727 728 729 730 731 732 733 734 735 736 737 738 739
        case ECONNRESET:        return WSAECONNRESET;
        case ENOBUFS:           return WSAENOBUFS;
        case EISCONN:           return WSAEISCONN;
        case ENOTCONN:          return WSAENOTCONN;
        case ESHUTDOWN:         return WSAESHUTDOWN;
        case ETOOMANYREFS:      return WSAETOOMANYREFS;
        case ETIMEDOUT:         return WSAETIMEDOUT;
        case ECONNREFUSED:      return WSAECONNREFUSED;
        case ELOOP:             return WSAELOOP;
        case ENAMETOOLONG:      return WSAENAMETOOLONG;
        case EHOSTDOWN:         return WSAEHOSTDOWN;
        case EHOSTUNREACH:      return WSAEHOSTUNREACH;
        case ENOTEMPTY:         return WSAENOTEMPTY;
740
#ifdef EPROCLIM
741
        case EPROCLIM:          return WSAEPROCLIM;
742 743
#endif
#ifdef EUSERS
744
        case EUSERS:            return WSAEUSERS;
745 746
#endif
#ifdef EDQUOT
747
        case EDQUOT:            return WSAEDQUOT;
748 749
#endif
#ifdef ESTALE
750
        case ESTALE:            return WSAESTALE;
751 752
#endif
#ifdef EREMOTE
753
        case EREMOTE:           return WSAEREMOTE;
754
#endif
755
    default: errno=err; perror("sock_set_error"); return WSAEFAULT;
756 757 758
    }
}

759 760 761 762 763 764
/* set the last error depending on errno */
static void sock_set_error(void)
{
    set_error( sock_get_error( errno ) );
}

765 766 767 768 769
/* create a socket */
DECL_HANDLER(create_socket)
{
    struct object *obj;

770
    reply->handle = 0;
771
    if ((obj = create_socket( req->family, req->type, req->protocol, req->flags )) != NULL)
772
    {
773
        reply->handle = alloc_handle( current->process, obj, req->access, req->inherit );
774 775 776 777 778 779 780
        release_object( obj );
    }
}

/* accept a socket */
DECL_HANDLER(accept_socket)
{
781
    struct sock *sock;
782

783
    reply->handle = 0;
784
    if ((sock = accept_socket( req->lhandle )) != NULL)
785
    {
786 787 788 789
        reply->handle = alloc_handle( current->process, &sock->obj, req->access, req->inherit );
        sock->wparam = reply->handle;  /* wparam for message is the socket handle */
        sock_reselect( sock );
        release_object( &sock->obj );
790 791 792 793 794 795 796
    }
}

/* set socket event parameters */
DECL_HANDLER(set_socket_event)
{
    struct sock *sock;
797
    struct event *old_event;
798
    int pollev;
799

800 801 802 803
    if (!(sock = (struct sock*)get_handle_obj( current->process, req->handle,
                                               GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE, &sock_ops)))
        return;
    old_event = sock->event;
804
    sock->mask    = req->mask;
805 806 807 808 809 810
    sock->event   = NULL;
    sock->window  = req->window;
    sock->message = req->msg;
    sock->wparam  = req->handle;  /* wparam is the socket handle */
    if (req->event) sock->event = get_event_obj( current->process, req->event, EVENT_MODIFY_STATE );

811
    if (debug_level && sock->event) fprintf(stderr, "event ptr: %p\n", sock->event);
812 813

    pollev = sock_reselect( sock );
814
    if ( pollev ) sock_try_event( sock, pollev );
815

816
    if (sock->mask)
817
        sock->state |= FD_WINE_NONBLOCKING;
818

819
    /* if a network event is pending, signal the event object
820
       it is possible that FD_CONNECT or FD_ACCEPT network events has happened
821
       before a WSAEventSelect() was done on it.
822
       (when dealing with Asynchronous socket)  */
823
    if (sock->pmask & sock->mask) sock_wake_up( sock, pollev );
824 825

    if (old_event) release_object( old_event ); /* we're through with it */
826 827 828 829 830 831 832 833 834 835 836
    release_object( &sock->obj );
}

/* get socket event parameters */
DECL_HANDLER(get_socket_event)
{
    struct sock *sock;

    sock=(struct sock*)get_handle_obj(current->process,req->handle,GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,&sock_ops);
    if (!sock)
    {
837 838 839 840 841
        reply->mask  = 0;
        reply->pmask = 0;
        reply->state = 0;
        set_error( WSAENOTSOCK );
        return;
842
    }
843 844 845 846
    reply->mask  = sock->mask;
    reply->pmask = sock->pmask;
    reply->state = sock->state;
    set_reply_data( sock->errors, min( get_reply_max_size(), sizeof(sock->errors) ));
847

848 849
    if (req->service)
    {
850
        if (req->c_event)
851
        {
852 853 854
            struct event *cevent = get_event_obj( current->process, req->c_event,
                                                  EVENT_MODIFY_STATE );
            if (cevent)
855 856 857 858
            {
                reset_event( cevent );
                release_object( cevent );
            }
859
        }
860 861
        sock->pmask = 0;
        sock_reselect( sock );
862 863 864 865 866 867 868 869
    }
    release_object( &sock->obj );
}

/* re-enable pending socket events */
DECL_HANDLER(enable_socket_event)
{
    struct sock *sock;
870
    int pollev;
871

872 873 874 875
    if (!(sock = (struct sock*)get_handle_obj( current->process, req->handle,
                                               GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE, &sock_ops)))
        return;

876 877
    sock->pmask &= ~req->mask; /* is this safe? */
    sock->hmask &= ~req->mask;
878 879
    if ( req->mask & FD_READ )
        sock->hmask &= ~FD_CLOSE;
880 881
    sock->state |= req->sstate;
    sock->state &= ~req->cstate;
882
    if ( sock->type != SOCK_STREAM ) sock->state &= ~STREAM_FLAG_MASK;
883 884

    pollev = sock_reselect( sock );
885
    if ( pollev ) sock_try_event( sock, pollev );
886

887 888
    release_object( &sock->obj );
}
889 890 891 892 893 894 895 896 897

DECL_HANDLER(set_socket_deferred)
{
    struct sock *sock, *acceptsock;

    sock=(struct sock*)get_handle_obj( current->process,req->handle,
                                       GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,&sock_ops );
    if ( !sock )
    {
898
        set_error( WSAENOTSOCK );
899 900 901 902 903 904
        return;
    }
    acceptsock = (struct sock*)get_handle_obj( current->process,req->deferred,
                                               GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,&sock_ops );
    if ( !acceptsock )
    {
905 906
        release_object( sock );
        set_error( WSAENOTSOCK );
907 908 909
        return;
    }
    sock->deferred = acceptsock;
910
    release_object( sock );
911
}