sock.c 29.2 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
 * 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
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19
 *
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 51
#include "ntstatus.h"
#define WIN32_NO_STATUS
52
#include "windef.h"
53
#include "winternl.h"
54

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

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

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

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

static int sock_get_poll_events( struct fd *fd );
static void sock_poll_event( struct fd *fd, int event );
97
static enum server_fd_type sock_get_fd_type( struct fd *fd );
98
static void sock_queue_async( struct fd *fd, const async_data_t *data, int type, int count );
99
static void sock_reselect_async( struct fd *fd, struct async_queue *queue );
100
static void sock_cancel_async( struct fd *fd );
101

102
static int sock_get_error( int err );
103 104 105 106
static void sock_set_error(void);

static const struct object_ops sock_ops =
{
107 108
    sizeof(struct sock),          /* size */
    sock_dump,                    /* dump */
109
    no_get_type,                  /* get_type */
110 111 112 113
    add_queue,                    /* add_queue */
    remove_queue,                 /* remove_queue */
    sock_signaled,                /* signaled */
    no_satisfied,                 /* satisfied */
114
    no_signal,                    /* signal */
115
    sock_get_fd,                  /* get_fd */
116
    default_fd_map_access,        /* map_access */
117 118
    default_get_sd,               /* get_sd */
    default_set_sd,               /* set_sd */
119
    no_lookup_name,               /* lookup_name */
120
    no_open_file,                 /* open_file */
121
    fd_close_handle,              /* close_handle */
122 123 124 125 126
    sock_destroy                  /* destroy */
};

static const struct fd_ops sock_fd_ops =
{
127 128 129
    sock_get_poll_events,         /* get_poll_events */
    sock_poll_event,              /* poll_event */
    no_flush,                     /* flush */
130
    sock_get_fd_type,             /* get_file_info */
131
    default_fd_ioctl,             /* ioctl */
132
    sock_queue_async,             /* queue_async */
133
    sock_reselect_async,          /* reselect_async */
134
    sock_cancel_async             /* cancel_async */
135 136
};

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

/* 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 */
};

156 157 158 159 160 161 162 163 164 165 166
/* 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;

167
static sock_shutdown_t sock_check_pollhup(void)
168 169 170 171 172 173
{
    sock_shutdown_t ret = SOCK_SHUTDOWN_ERROR;
    int fd[2], n;
    struct pollfd pfd;
    char dummy;

174 175
    if ( socketpair( AF_UNIX, SOCK_STREAM, 0, fd ) ) goto out;
    if ( shutdown( fd[0], 1 ) ) goto out;
176 177 178 179 180

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

181
    n = poll( &pfd, 1, 0 );
182 183 184 185
    if ( n != 1 ) goto out; /* error or timeout */
    if ( pfd.revents & POLLHUP )
        ret = SOCK_SHUTDOWN_POLLHUP;
    else if ( pfd.revents & POLLIN &&
186
              read( fd[1], &dummy, 1 ) == 0 )
187 188 189
        ret = SOCK_SHUTDOWN_EOF;

out:
190 191
    close( fd[0] );
    close( fd[1] );
192 193 194 195 196
    return ret;
}

void sock_init(void)
{
197
    sock_shutdown_type = sock_check_pollhup();
198 199 200 201

    switch ( sock_shutdown_type )
    {
    case SOCK_SHUTDOWN_EOF:
202
        if (debug_level) fprintf( stderr, "sock_init: shutdown() causes EOF\n" );
203 204
        break;
    case SOCK_SHUTDOWN_POLLHUP:
205
        if (debug_level) fprintf( stderr, "sock_init: shutdown() causes POLLHUP\n" );
206 207
        break;
    default:
208
        fprintf( stderr, "sock_init: ERROR in sock_check_pollhup()\n" );
209 210 211
        sock_shutdown_type = SOCK_SHUTDOWN_EOF;
    }
}
212

213
static int sock_reselect( struct sock *sock )
214
{
215
    int ev = sock_get_poll_events( sock->fd );
216

217
    if (debug_level)
218
        fprintf(stderr,"sock_reselect(%p): new mask %x\n", sock, ev);
219

220 221
    if (!sock->polling)  /* FIXME: should find a better way to do this */
    {
222
        /* previously unconnected socket, is this reselect supposed to connect it? */
223
        if (!(sock->state & ~FD_WINE_NONBLOCKING)) return 0;
224
        /* ok, it is, attach it to the wineserver's main poll loop */
225
        sock->polling = 1;
226 227
    }
    /* update condition mask */
228
    set_fd_events( sock->fd, ev );
229 230 231 232 233
    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 */
234
static void sock_try_event( struct sock *sock, int event )
235
{
236
    event = check_fd_events( sock->fd, event );
237
    if (event)
238
    {
239 240
        if ( debug_level ) fprintf( stderr, "sock_try_event: %x\n", event );
        sock_poll_event( sock->fd, event );
241
    }
242
}
243

244
/* wake anybody waiting on the socket event or send the associated message */
245
static void sock_wake_up( struct sock *sock, int pollev )
246 247 248
{
    unsigned int events = sock->pmask & sock->mask;
    int i;
249
    int async_active = 0;
250

251
    if ( pollev & (POLLIN|POLLPRI) && async_waiting( sock->read_q ))
252
    {
253 254 255 256 257 258 259 260 261
        if (debug_level) fprintf( stderr, "activating read queue for socket %p\n", sock );
        async_wake_up( sock->read_q, STATUS_ALERTED );
        async_active = 1;
    }
    if ( pollev & POLLOUT && async_waiting( sock->write_q ))
    {
        if (debug_level) fprintf( stderr, "activating write queue for socket %p\n", sock );
        async_wake_up( sock->write_q, STATUS_ALERTED );
        async_active = 1;
262 263 264 265 266 267
    }

    /* 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;

268 269 270 271 272 273 274
    if (sock->event)
    {
        if (debug_level) fprintf(stderr, "signalling events %x ptr %p\n", events, sock->event );
        set_event( sock->event );
    }
    if (sock->window)
    {
275
        if (debug_level) fprintf(stderr, "signalling events %x win %p\n", events, sock->window );
276 277 278 279 280 281
        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);
282
                post_message( sock->window, sock->message, (unsigned long)sock->wparam, lparam );
283 284 285 286 287
            }
        }
        sock->pmask = 0;
        sock_reselect( sock );
    }
288 289
}

290
static inline int sock_error( struct fd *fd )
291
{
292
    unsigned int optval = 0, optlen;
293

294
    optlen = sizeof(optval);
295
    getsockopt( get_unix_fd(fd), SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
296
    return optval ? sock_get_error(optval) : 0;
297 298
}

299
static void sock_poll_event( struct fd *fd, int event )
300
{
301
    struct sock *sock = get_fd_user( fd );
302
    int hangup_seen = 0;
303

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

            /* 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 */
358
            nr  = recv( get_unix_fd( fd ), &dummy, 1, MSG_PEEK );
359
            if ( nr > 0 )
360 361 362
            {
                /* incoming data */
                sock->pmask |= FD_READ;
363
                sock->hmask |= (FD_READ|FD_CLOSE);
364 365
                sock->errors[FD_READ_BIT] = 0;
                if (debug_level)
366
                    fprintf(stderr, "socket %p is readable\n", sock );
367
            }
368
            else if ( nr == 0 )
369
                hangup_seen = 1;
370 371 372 373 374 375 376 377 378
            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 )
379
                        fprintf( stderr, "recv error on socket %p: %d\n", sock, errno );
380 381 382 383
                    event = POLLERR;
                }
            }

384
        }
385 386 387 388 389 390 391 392 393 394
        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)
395
                fprintf(stderr, "socket %p is readable\n", sock );
396 397

        }
398

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

430 431 432
    if ( sock->pmask & FD_CLOSE || event & (POLLERR|POLLHUP) )
    {
        if ( debug_level )
433
            fprintf( stderr, "removing socket %p from select loop\n", sock );
434
        set_fd_events( sock->fd, -1 );
435 436 437
    }
    else
        sock_reselect( sock );
438

439
    /* wake up anyone waiting for whatever just happened */
440
    if ( sock->pmask & sock->mask || sock->flags & WSA_FLAG_OVERLAPPED ) sock_wake_up( sock, event );
441 442 443 444 445 446 447 448 449 450

    /* 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 );
451
    printf( "Socket fd=%p, state=%x, mask=%x, pending=%x, held=%x\n",
452
            sock->fd, sock->state,
453
            sock->mask, sock->pmask, sock->hmask );
454 455
}

456
static int sock_signaled( struct object *obj, struct thread *thread )
457
{
458
    struct sock *sock = (struct sock *)obj;
459 460
    assert( obj->ops == &sock_ops );

461
    return check_fd_events( sock->fd, sock_get_poll_events( sock->fd ) ) != 0;
462 463
}

464
static int sock_get_poll_events( struct fd *fd )
465
{
466
    struct sock *sock = get_fd_user( fd );
467 468 469
    unsigned int mask = sock->mask & sock->state & ~sock->hmask;
    int ev = 0;

470
    assert( sock->obj.ops == &sock_ops );
471

472
    if (sock->state & FD_CONNECT)
473 474
        /* connecting, wait for writable */
        return POLLOUT;
475
    if (sock->state & FD_WINE_LISTENING)
476 477 478
        /* listening, wait for readable */
        return (sock->hmask & FD_ACCEPT) ? 0 : POLLIN;

479 480
    if (mask & FD_READ  || async_waiting( sock->read_q )) ev |= POLLIN | POLLPRI;
    if (mask & FD_WRITE || async_waiting( sock->write_q )) ev |= POLLOUT;
481 482
    /* 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) )
483 484
        ev |= POLLIN;

485
    return ev;
486 487
}

488
static enum server_fd_type sock_get_fd_type( struct fd *fd )
489
{
490
    return FD_TYPE_SOCKET;
491 492
}

493
static void sock_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
494
{
495
    struct sock *sock = get_fd_user( fd );
496
    struct async_queue *queue;
497
    int pollev;
498

499
    assert( sock->obj.ops == &sock_ops );
500

501
    switch (type)
502 503
    {
    case ASYNC_TYPE_READ:
504 505
        if (!sock->read_q && !(sock->read_q = create_async_queue( sock->fd ))) return;
        queue = sock->read_q;
506
        sock->hmask &= ~FD_CLOSE;
507 508
        break;
    case ASYNC_TYPE_WRITE:
509 510
        if (!sock->write_q && !(sock->write_q = create_async_queue( sock->fd ))) return;
        queue = sock->write_q;
511 512 513 514 515 516
        break;
    default:
        set_error( STATUS_INVALID_PARAMETER );
        return;
    }

517 518
    if ( ( !( sock->state & FD_READ ) && type == ASYNC_TYPE_READ  ) ||
         ( !( sock->state & FD_WRITE ) && type == ASYNC_TYPE_WRITE ) )
519
    {
520 521 522 523
        set_error( STATUS_PIPE_DISCONNECTED );
    }
    else
    {
524 525 526
        struct async *async;
        if (!(async = create_async( current, queue, data ))) return;
        release_object( async );
527
        set_error( STATUS_PENDING );
528 529
    }

530 531 532 533
    pollev = sock_reselect( sock );
    if ( pollev ) sock_try_event( sock, pollev );
}

534 535 536 537 538 539 540
static void sock_reselect_async( struct fd *fd, struct async_queue *queue )
{
    struct sock *sock = get_fd_user( fd );
    int events = sock_reselect( sock );
    if (events) sock_try_event( sock, events );
}

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

546 547
    async_wake_up( sock->read_q, STATUS_CANCELLED );
    async_wake_up( sock->write_q, STATUS_CANCELLED );
548 549
}

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

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

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

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

566 567
    free_async_queue( sock->read_q );
    free_async_queue( sock->write_q );
568
    if (sock->event) release_object( sock->event );
569 570 571 572 573 574
    if (sock->fd)
    {
        /* shut the socket down to force pending poll() calls in the client to return */
        shutdown( get_unix_fd(sock->fd), SHUT_RDWR );
        release_object( sock->fd );
    }
575 576 577
}

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

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

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

631
    sock = (struct sock *)get_handle_obj( current->process, handle, FILE_READ_DATA, &sock_ops );
632 633 634
    if (!sock)
    	return NULL;

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

        /* 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.
         */
647
        unsigned int slen = sizeof(saddr);
648
        acceptfd = accept( get_unix_fd(sock->fd), &saddr, &slen);
649 650
        if (acceptfd==-1)
        {
651 652 653 654
            sock_set_error();
            release_object( sock );
            return NULL;
        }
655
        if (!(acceptsock = alloc_object( &sock_ops )))
656
        {
657
            close( acceptfd );
658 659 660
            release_object( sock );
            return NULL;
        }
661

662 663 664 665 666 667 668 669
        /* 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;
670
        acceptsock->polling = 0;
671 672
        acceptsock->type    = sock->type;
        acceptsock->family  = sock->family;
673 674 675 676 677 678
        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;
679
        acceptsock->deferred = NULL;
680 681
        acceptsock->read_q  = NULL;
        acceptsock->write_q = NULL;
682 683
        if (!(acceptsock->fd = create_anonymous_fd( &sock_fd_ops, acceptfd, &acceptsock->obj,
                                                    get_fd_options( sock->fd ) )))
684 685 686 687 688
        {
            release_object( acceptsock );
            release_object( sock );
            return NULL;
        }
689
    }
690 691 692
    clear_error();
    sock->pmask &= ~FD_ACCEPT;
    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 704
        case EINTR:             return WSAEINTR;
        case EBADF:             return WSAEBADF;
705
        case EPERM:
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
        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;
729
        case EPIPE:
730 731 732 733 734 735 736 737 738 739 740 741 742
        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;
743
#ifdef EPROCLIM
744
        case EPROCLIM:          return WSAEPROCLIM;
745 746
#endif
#ifdef EUSERS
747
        case EUSERS:            return WSAEUSERS;
748 749
#endif
#ifdef EDQUOT
750
        case EDQUOT:            return WSAEDQUOT;
751 752
#endif
#ifdef ESTALE
753
        case ESTALE:            return WSAESTALE;
754 755
#endif
#ifdef EREMOTE
756
        case EREMOTE:           return WSAEREMOTE;
757
#endif
758 759 760 761
        default:
            errno = err;
            perror("wineserver: sock_get_error() can't map error");
            return WSAEFAULT;
762 763 764
    }
}

765 766 767 768 769 770
/* set the last error depending on errno */
static void sock_set_error(void)
{
    set_error( sock_get_error( errno ) );
}

771 772 773 774 775
/* create a socket */
DECL_HANDLER(create_socket)
{
    struct object *obj;

776
    reply->handle = 0;
777
    if ((obj = create_socket( req->family, req->type, req->protocol, req->flags )) != NULL)
778
    {
779
        reply->handle = alloc_handle( current->process, obj, req->access, req->attributes );
780 781 782 783 784 785 786
        release_object( obj );
    }
}

/* accept a socket */
DECL_HANDLER(accept_socket)
{
787
    struct sock *sock;
788

789
    reply->handle = 0;
790
    if ((sock = accept_socket( req->lhandle )) != NULL)
791
    {
792
        reply->handle = alloc_handle( current->process, &sock->obj, req->access, req->attributes );
793 794 795
        sock->wparam = reply->handle;  /* wparam for message is the socket handle */
        sock_reselect( sock );
        release_object( &sock->obj );
796 797 798 799 800 801 802
    }
}

/* set socket event parameters */
DECL_HANDLER(set_socket_event)
{
    struct sock *sock;
803
    struct event *old_event;
804
    int pollev;
805

806 807
    if (!(sock = (struct sock *)get_handle_obj( current->process, req->handle,
                                                FILE_WRITE_ATTRIBUTES, &sock_ops))) return;
808
    old_event = sock->event;
809
    sock->mask    = req->mask;
810
    sock->hmask   &= ~req->mask; /* re-enable held events */
811 812 813 814 815 816
    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 );

817
    if (debug_level && sock->event) fprintf(stderr, "event ptr: %p\n", sock->event);
818 819

    pollev = sock_reselect( sock );
820
    if ( pollev ) sock_try_event( sock, pollev );
821

822
    if (sock->mask)
823
        sock->state |= FD_WINE_NONBLOCKING;
824

825
    /* if a network event is pending, signal the event object
826
       it is possible that FD_CONNECT or FD_ACCEPT network events has happened
827
       before a WSAEventSelect() was done on it.
828
       (when dealing with Asynchronous socket)  */
829
    if (sock->pmask & sock->mask) sock_wake_up( sock, pollev );
830 831

    if (old_event) release_object( old_event ); /* we're through with it */
832 833 834 835 836 837 838 839
    release_object( &sock->obj );
}

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

840
    sock = (struct sock *)get_handle_obj( current->process, req->handle, FILE_READ_ATTRIBUTES, &sock_ops );
841 842
    if (!sock)
    {
843 844 845 846 847
        reply->mask  = 0;
        reply->pmask = 0;
        reply->state = 0;
        set_error( WSAENOTSOCK );
        return;
848
    }
849 850 851 852
    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) ));
853

854 855
    if (req->service)
    {
856
        if (req->c_event)
857
        {
858 859 860
            struct event *cevent = get_event_obj( current->process, req->c_event,
                                                  EVENT_MODIFY_STATE );
            if (cevent)
861 862 863 864
            {
                reset_event( cevent );
                release_object( cevent );
            }
865
        }
866 867
        sock->pmask = 0;
        sock_reselect( sock );
868 869 870 871 872 873 874 875
    }
    release_object( &sock->obj );
}

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

878
    if (!(sock = (struct sock*)get_handle_obj( current->process, req->handle,
879
                                               FILE_WRITE_ATTRIBUTES, &sock_ops)))
880 881
        return;

882 883
    sock->pmask &= ~req->mask; /* is this safe? */
    sock->hmask &= ~req->mask;
884 885
    if ( req->mask & FD_READ )
        sock->hmask &= ~FD_CLOSE;
886 887
    sock->state |= req->sstate;
    sock->state &= ~req->cstate;
888
    if ( sock->type != SOCK_STREAM ) sock->state &= ~STREAM_FLAG_MASK;
889 890

    pollev = sock_reselect( sock );
891
    if ( pollev ) sock_try_event( sock, pollev );
892

893 894
    release_object( &sock->obj );
}
895 896 897 898 899

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

900
    sock=(struct sock *)get_handle_obj( current->process, req->handle, FILE_WRITE_ATTRIBUTES, &sock_ops );
901 902
    if ( !sock )
    {
903
        set_error( WSAENOTSOCK );
904 905
        return;
    }
906
    acceptsock = (struct sock *)get_handle_obj( current->process, req->deferred, 0, &sock_ops );
907 908
    if ( !acceptsock )
    {
909 910
        release_object( sock );
        set_error( WSAENOTSOCK );
911 912 913
        return;
    }
    sock->deferred = acceptsock;
914
    release_object( sock );
915
}