sock.c 125 KB
Newer Older
1 2 3
/*
 * Server-side socket management
 *
4
 * Copyright (C) 1999 Marcus Meissner, Ove Kåven
5
 *
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 36 37 38
#ifdef HAVE_IFADDRS_H
# include <ifaddrs.h>
#endif
#ifdef HAVE_NET_IF_H
# include <net/if.h>
#endif
39 40 41
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
42 43 44
#ifdef HAVE_NETINET_TCP_H
# include <netinet/tcp.h>
#endif
45
#include <poll.h>
46 47
#include <sys/time.h>
#include <sys/types.h>
48
#include <sys/socket.h>
49
#include <sys/ioctl.h>
50 51 52
#ifdef HAVE_SYS_FILIO_H
# include <sys/filio.h>
#endif
53 54
#include <time.h>
#include <unistd.h>
55
#include <limits.h>
56 57 58
#ifdef HAVE_LINUX_FILTER_H
# include <linux/filter.h>
#endif
59 60 61
#ifdef HAVE_LINUX_RTNETLINK_H
# include <linux/rtnetlink.h>
#endif
62

63 64
#ifdef HAVE_NETIPX_IPX_H
# include <netipx/ipx.h>
65
# define HAS_IPX
66 67 68 69 70 71 72 73
#elif defined(HAVE_LINUX_IPX_H)
# ifdef HAVE_ASM_TYPES_H
#  include <asm/types.h>
# endif
# ifdef HAVE_LINUX_TYPES_H
#  include <linux/types.h>
# endif
# include <linux/ipx.h>
74 75 76
# ifdef SOL_IPX
#  define HAS_IPX
# endif
77 78 79 80 81 82 83 84 85 86
#endif

#ifdef HAVE_LINUX_IRDA_H
# ifdef HAVE_LINUX_TYPES_H
#  include <linux/types.h>
# endif
# include <linux/irda.h>
# define HAS_IRDA
#endif

87 88
#include "ntstatus.h"
#define WIN32_NO_STATUS
89
#include "windef.h"
90
#include "winternl.h"
91
#include "winerror.h"
92 93
#define USE_WS_PREFIX
#include "winsock2.h"
94
#include "ws2tcpip.h"
95
#include "wsipx.h"
96
#include "af_irda.h"
97
#include "wine/afd.h"
98
#include "wine/rbtree.h"
99

100
#include "process.h"
101
#include "file.h"
102 103 104
#include "handle.h"
#include "thread.h"
#include "request.h"
105
#include "user.h"
106

107 108 109 110
#if defined(linux) && !defined(IP_UNICAST_IF)
#define IP_UNICAST_IF 50
#endif

111 112
static const char magic_loopback_addr[] = {127, 12, 34, 56};

113 114 115 116 117 118 119 120 121
union win_sockaddr
{
    struct WS_sockaddr addr;
    struct WS_sockaddr_in in;
    struct WS_sockaddr_in6 in6;
    struct WS_sockaddr_ipx ipx;
    SOCKADDR_IRDA irda;
};

122 123 124 125 126 127 128 129 130 131 132 133 134
union unix_sockaddr
{
    struct sockaddr addr;
    struct sockaddr_in in;
    struct sockaddr_in6 in6;
#ifdef HAS_IPX
    struct sockaddr_ipx ipx;
#endif
#ifdef HAS_IRDA
    struct sockaddr_irda irda;
#endif
};

135 136 137 138 139 140 141 142
static struct list poll_list = LIST_INIT( poll_list );

struct poll_req
{
    struct list entry;
    struct async *async;
    struct iosb *iosb;
    struct timeout_user *timeout;
143
    timeout_t orig_timeout;
144
    int exclusive;
145
    int pending;
146 147 148 149
    unsigned int count;
    struct
    {
        struct sock *sock;
150
        int mask;
151 152 153
        obj_handle_t handle;
        int flags;
        unsigned int status;
154 155 156
    } sockets[1];
};

157 158 159 160
struct accept_req
{
    struct list entry;
    struct async *async;
161
    struct iosb *iosb;
162
    struct sock *sock, *acceptsock;
163 164 165 166
    int accepted;
    unsigned int recv_len, local_len;
};

167 168 169 170 171 172 173 174
struct connect_req
{
    struct async *async;
    struct iosb *iosb;
    struct sock *sock;
    unsigned int addr_len, send_len, send_cursor;
};

175 176 177 178 179 180
struct send_req
{
    struct iosb *iosb;
    struct sock *sock;
};

181 182 183 184 185 186 187 188 189
enum connection_state
{
    SOCK_LISTENING,
    SOCK_UNCONNECTED,
    SOCK_CONNECTING,
    SOCK_CONNECTED,
    SOCK_CONNECTIONLESS,
};

190 191 192 193
struct bound_addr
{
    struct rb_entry entry;
    union unix_sockaddr addr;
194
    int match_any_addr;
195 196 197
    int reuse_count;
};

198 199
#define MAX_ICMP_HISTORY_LENGTH 8

200 201
#define MIN_RCVBUF 65536

202 203 204
struct sock
{
    struct object       obj;         /* object header */
205
    struct fd          *fd;          /* socket file descriptor */
206
    enum connection_state state;     /* connection state */
207
    unsigned int        mask;        /* event mask */
208
    /* pending AFD_POLL_* events which have not yet been reported to the application */
209
    unsigned int        pending_events;
210 211
    /* AFD_POLL_* events which have already been reported and should not be
     * selected for again until reset by a relevant call.
212
     *
213 214 215
     * For example, if AFD_POLL_READ is set here and not in pending_events, it
     * has already been reported and consumed, and we should not report it
     * again, even if POLLIN is signaled, until it is reset by e.g recv().
216 217 218 219 220
     *
     * If an event has been signaled and not consumed yet, it will be set in
     * both pending_events and reported_events (as we should only ever report
     * any event once until it is reset.) */
    unsigned int        reported_events;
221
    unsigned short      proto;       /* socket protocol */
222 223
    unsigned short      type;        /* socket type */
    unsigned short      family;      /* socket family */
224
    struct event       *event;       /* event object */
225 226
    user_handle_t       window;      /* window to send the message to */
    unsigned int        message;     /* message to send */
227
    obj_handle_t        wparam;      /* message wparam (socket handle) */
228
    int                 errors[AFD_POLL_BIT_COUNT]; /* event errors */
229
    timeout_t           connect_time;/* time the socket was connected */
230
    struct sock        *deferred;    /* socket that waits for a deferred accept */
231 232 233
    struct async_queue  read_q;      /* queue for asynchronous reads */
    struct async_queue  write_q;     /* queue for asynchronous writes */
    struct async_queue  ifchange_q;  /* queue for interface change notifications */
234
    struct async_queue  accept_q;    /* queue for asynchronous accepts */
235
    struct async_queue  connect_q;   /* queue for asynchronous connects */
236
    struct async_queue  poll_q;      /* queue for asynchronous polls */
237 238
    struct object      *ifchange_obj; /* the interface change notification object */
    struct list         ifchange_entry; /* entry in ifchange notification list */
239 240
    struct list         accept_list; /* list of pending accept requests */
    struct accept_req  *accept_recv_req; /* pending accept-into request which will recv on this socket */
241
    struct connect_req *connect_req; /* pending connection request */
242
    struct poll_req    *main_poll;   /* main poll */
243 244
    union win_sockaddr  addr;        /* socket name */
    int                 addr_len;    /* socket name length */
245 246
    union win_sockaddr  peer_addr;   /* peer name */
    int                 peer_addr_len; /* peer name length */
247
    unsigned int        rcvbuf;      /* advisory recv buffer size */
248
    unsigned int        sndbuf;      /* advisory send buffer size */
249
    unsigned int        rcvtimeo;    /* receive timeout in ms */
250
    unsigned int        sndtimeo;    /* send timeout in ms */
251 252 253 254 255 256
    struct
    {
        unsigned short icmp_id;
        unsigned short icmp_seq;
    }
    icmp_fixup_data[MAX_ICMP_HISTORY_LENGTH]; /* Sent ICMP packets history used to fixup reply id. */
257
    struct bound_addr  *bound_addr[2]; /* Links to the entries in bound addresses tree. */
258
    unsigned int        icmp_fixup_data_len;  /* Sent ICMP packets history length. */
259 260
    unsigned int        rd_shutdown : 1; /* is the read end shut down? */
    unsigned int        wr_shutdown : 1; /* is the write end shut down? */
261
    unsigned int        wr_shutdown_pending : 1; /* is a write shutdown pending? */
262
    unsigned int        hangup : 1;  /* has the read end received a hangup? */
263
    unsigned int        aborted : 1; /* did we get a POLLERR or irregular POLLHUP? */
264
    unsigned int        nonblocking : 1; /* is the socket nonblocking? */
265
    unsigned int        bound : 1;   /* is the socket bound? */
266
    unsigned int        reset : 1;   /* did we get a TCP reset? */
267
    unsigned int        reuseaddr : 1; /* winsock SO_REUSEADDR option value */
268
    unsigned int        exclusiveaddruse : 1; /* winsock SO_EXCLUSIVEADDRUSE option value */
269 270
};

271 272 273 274 275 276 277 278
static int is_tcp_socket( struct sock *sock )
{
    return sock->type == WS_SOCK_STREAM && (sock->family == WS_AF_INET || sock->family == WS_AF_INET6);
}

static int addr_compare( const void *key, const struct wine_rb_entry *entry )
{
    const struct bound_addr *bound_addr = RB_ENTRY_VALUE(entry, struct bound_addr, entry);
279
    const struct bound_addr *addr = key;
280

281 282
    if (addr->addr.addr.sa_family != bound_addr->addr.addr.sa_family)
        return addr->addr.addr.sa_family < bound_addr->addr.addr.sa_family ? -1 : 1;
283

284
    if (addr->addr.addr.sa_family == AF_INET)
285
    {
286 287
        if (addr->addr.in.sin_port != bound_addr->addr.in.sin_port)
            return addr->addr.in.sin_port < bound_addr->addr.in.sin_port ? -1 : 1;
288 289
        if (bound_addr->match_any_addr || addr->match_any_addr
            || addr->addr.in.sin_addr.s_addr == bound_addr->addr.in.sin_addr.s_addr)
290
            return 0;
291
        return addr->addr.in.sin_addr.s_addr < bound_addr->addr.in.sin_addr.s_addr ? -1 : 1;
292 293
    }

294 295 296
    assert( addr->addr.addr.sa_family == AF_INET6 );
    if (addr->addr.in6.sin6_port != bound_addr->addr.in6.sin6_port)
        return addr->addr.in6.sin6_port < bound_addr->addr.in6.sin6_port ? -1 : 1;
297
    if (bound_addr->match_any_addr || addr->match_any_addr) return 0;
298
    return memcmp( &addr->addr.in6.sin6_addr, &bound_addr->addr.in6.sin6_addr, sizeof(addr->addr.in6.sin6_addr) );
299 300
}

301
static int ipv4addr_from_v6( union unix_sockaddr *v4addr, const struct sockaddr_in6 *in6, int map_unspecified )
302 303 304
{
    v4addr->in.sin_family = AF_INET;
    v4addr->in.sin_port = in6->sin6_port;
305 306

    if (map_unspecified && IN6_IS_ADDR_UNSPECIFIED(&in6->sin6_addr))
307
    {
308
        v4addr->in.sin_addr.s_addr = htonl( INADDR_ANY );
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
        return 1;
    }
    if (IN6_IS_ADDR_V4COMPAT(&in6->sin6_addr) || IN6_IS_ADDR_V4MAPPED(&in6->sin6_addr))
    {
        memcpy( &v4addr->in.sin_addr.s_addr, &in6->sin6_addr.s6_addr[12], sizeof(v4addr->in.sin_addr.s_addr) );
        return 1;
    }
    return 0;
}

static struct rb_tree bound_addresses_tree = { addr_compare };

static int should_track_conflicts_for_addr( struct sock *sock, const union unix_sockaddr *addr )
{
    if (!is_tcp_socket( sock )) return 0;

    if (sock->family == WS_AF_INET && addr->addr.sa_family == AF_INET && addr->in.sin_port)
        return 1;
    else if (sock->family == WS_AF_INET6 && addr->addr.sa_family == AF_INET6 && addr->in6.sin6_port)
        return 1;

    return 0;
}

333 334 335 336 337 338 339 340 341
static int is_any_addr( const union unix_sockaddr *addr )
{
    if (addr->addr.sa_family == AF_INET && addr->in.sin_addr.s_addr == htonl( INADDR_ANY ))
        return 1;
    if (addr->addr.sa_family == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&addr->in6.sin6_addr))
        return 1;
    return 0;
}

342 343
static int check_addr_usage( struct sock *sock, const union unix_sockaddr *addr, int v6only )
{
344
    struct bound_addr *bound_addr, search_addr;
345 346 347 348
    struct rb_entry *entry;

    if (!should_track_conflicts_for_addr( sock, addr )) return 0;

349
    search_addr.addr = *addr;
350
    search_addr.match_any_addr = sock->exclusiveaddruse && is_any_addr( addr );
351 352

    if ((entry = rb_get( &bound_addresses_tree, &search_addr )))
353 354
    {
        bound_addr = WINE_RB_ENTRY_VALUE(entry, struct bound_addr, entry);
355 356
        if (bound_addr->reuse_count == -1 || !sock->reuseaddr)
        {
357 358
            set_error( sock->reuseaddr || bound_addr->match_any_addr
                       ? STATUS_ACCESS_DENIED : STATUS_SHARING_VIOLATION );
359 360
            return 1;
        }
361 362 363
    }

    if (sock->family != WS_AF_INET6 || v6only) return 0;
364
    if (!ipv4addr_from_v6( &search_addr.addr, &addr->in6, sock->exclusiveaddruse )) return 0;
365

366
    search_addr.match_any_addr = sock->exclusiveaddruse && is_any_addr( &search_addr.addr );
367
    if ((entry = rb_get( &bound_addresses_tree, &search_addr )))
368 369
    {
        bound_addr = WINE_RB_ENTRY_VALUE(entry, struct bound_addr, entry);
370 371
        if (bound_addr->reuse_count == -1 || !sock->reuseaddr)
        {
372 373
            set_error( sock->reuseaddr || bound_addr->match_any_addr
                       ? STATUS_ACCESS_DENIED : STATUS_SHARING_VIOLATION );
374 375
            return 1;
        }
376 377 378 379 380 381
    }
    return 0;
}

static struct bound_addr *register_bound_address( struct sock *sock, const union unix_sockaddr *addr )
{
382
    struct bound_addr *bound_addr, *temp;
383 384 385 386

    if (!(bound_addr = mem_alloc( sizeof(*bound_addr) )))
        return NULL;

387
    bound_addr->addr = *addr;
388
    bound_addr->match_any_addr = sock->exclusiveaddruse && is_any_addr( addr );
389 390

    if (rb_put( &bound_addresses_tree, bound_addr, &bound_addr->entry ))
391
    {
392 393 394
        temp = bound_addr;
        bound_addr = WINE_RB_ENTRY_VALUE(rb_get( &bound_addresses_tree, temp ), struct bound_addr, entry);
        free( temp );
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
        if (bound_addr->reuse_count == -1)
        {
            if (debug_level)
                fprintf( stderr, "register_bound_address: address being updated is already exclusively bound\n" );
            return NULL;
        }
        ++bound_addr->reuse_count;
    }
    else
    {
        bound_addr->reuse_count = sock->reuseaddr ? 1 : -1;
    }
    return bound_addr;
}

static void update_addr_usage( struct sock *sock, const union unix_sockaddr *addr, int v6only )
{
    union unix_sockaddr v4addr;

    assert( !sock->bound_addr[0] && !sock->bound_addr[1] );

    if (!should_track_conflicts_for_addr( sock, addr )) return;

    sock->bound_addr[0] = register_bound_address( sock, addr );

    if (sock->family != WS_AF_INET6 || v6only) return;
421 422

    if (!ipv4addr_from_v6( &v4addr, &addr->in6, sock->exclusiveaddruse )) return;
423 424 425 426

    sock->bound_addr[1] = register_bound_address( sock, &v4addr );
}

427
static void sock_dump( struct object *obj, int verbose );
428
static struct fd *sock_get_fd( struct object *obj );
429
static int sock_close_handle( struct object *obj, struct process *process, obj_handle_t handle );
430
static void sock_destroy( struct object *obj );
431 432
static struct object *sock_get_ifchange( struct sock *sock );
static void sock_release_ifchange( struct sock *sock );
433 434 435

static int sock_get_poll_events( struct fd *fd );
static void sock_poll_event( struct fd *fd, int event );
436
static enum server_fd_type sock_get_fd_type( struct fd *fd );
437
static void sock_ioctl( struct fd *fd, ioctl_code_t code, struct async *async );
438
static void sock_cancel_async( struct fd *fd, struct async *async );
439
static void sock_reselect_async( struct fd *fd, struct async_queue *queue );
440

441
static int accept_into_socket( struct sock *sock, struct sock *acceptsock );
442
static struct sock *accept_socket( struct sock *sock );
443
static int sock_get_ntstatus( int err );
444
static unsigned int sock_get_error( int err );
445 446
static void poll_socket( struct sock *poll_sock, struct async *async, int exclusive, timeout_t timeout,
                         unsigned int count, const struct afd_poll_socket_64 *sockets );
447 448 449

static const struct object_ops sock_ops =
{
450
    sizeof(struct sock),          /* size */
451
    &file_type,                   /* type */
452 453 454
    sock_dump,                    /* dump */
    add_queue,                    /* add_queue */
    remove_queue,                 /* remove_queue */
455
    default_fd_signaled,          /* signaled */
456
    no_satisfied,                 /* satisfied */
457
    no_signal,                    /* signal */
458
    sock_get_fd,                  /* get_fd */
459
    default_map_access,           /* map_access */
460 461
    default_get_sd,               /* get_sd */
    default_set_sd,               /* set_sd */
462
    no_get_full_name,             /* get_full_name */
463
    no_lookup_name,               /* lookup_name */
464 465
    no_link_name,                 /* link_name */
    NULL,                         /* unlink_name */
466
    no_open_file,                 /* open_file */
467
    no_kernel_obj_list,           /* get_kernel_obj_list */
468
    sock_close_handle,            /* close_handle */
469 470 471 472 473
    sock_destroy                  /* destroy */
};

static const struct fd_ops sock_fd_ops =
{
474 475
    sock_get_poll_events,         /* get_poll_events */
    sock_poll_event,              /* poll_event */
476
    sock_get_fd_type,             /* get_fd_type */
477 478 479
    no_fd_read,                   /* read */
    no_fd_write,                  /* write */
    no_fd_flush,                  /* flush */
480
    default_fd_get_file_info,     /* get_file_info */
481
    no_fd_get_volume_info,        /* get_volume_info */
482
    sock_ioctl,                   /* ioctl */
483
    sock_cancel_async,            /* cancel_async */
484
    no_fd_queue_async,            /* queue_async */
485
    sock_reselect_async           /* reselect_async */
486 487
};

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
static int sockaddr_from_unix( const union unix_sockaddr *uaddr, struct WS_sockaddr *wsaddr, socklen_t wsaddrlen )
{
    memset( wsaddr, 0, wsaddrlen );

    switch (uaddr->addr.sa_family)
    {
    case AF_INET:
    {
        struct WS_sockaddr_in win = {0};

        if (wsaddrlen < sizeof(win)) return -1;
        win.sin_family = WS_AF_INET;
        win.sin_port = uaddr->in.sin_port;
        memcpy( &win.sin_addr, &uaddr->in.sin_addr, sizeof(win.sin_addr) );
        memcpy( wsaddr, &win, sizeof(win) );
        return sizeof(win);
    }

    case AF_INET6:
    {
        struct WS_sockaddr_in6 win = {0};

510
        if (wsaddrlen < sizeof(win)) return -1;
511 512 513 514 515 516 517
        win.sin6_family = WS_AF_INET6;
        win.sin6_port = uaddr->in6.sin6_port;
        win.sin6_flowinfo = uaddr->in6.sin6_flowinfo;
        memcpy( &win.sin6_addr, &uaddr->in6.sin6_addr, sizeof(win.sin6_addr) );
#ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
        win.sin6_scope_id = uaddr->in6.sin6_scope_id;
#endif
518 519
        memcpy( wsaddr, &win, sizeof(win) );
        return sizeof(win);
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
    }

#ifdef HAS_IPX
    case AF_IPX:
    {
        struct WS_sockaddr_ipx win = {0};

        if (wsaddrlen < sizeof(win)) return -1;
        win.sa_family = WS_AF_IPX;
        memcpy( win.sa_netnum, &uaddr->ipx.sipx_network, sizeof(win.sa_netnum) );
        memcpy( win.sa_nodenum, &uaddr->ipx.sipx_node, sizeof(win.sa_nodenum) );
        win.sa_socket = uaddr->ipx.sipx_port;
        memcpy( wsaddr, &win, sizeof(win) );
        return sizeof(win);
    }
#endif

#ifdef HAS_IRDA
    case AF_IRDA:
    {
        SOCKADDR_IRDA win;

        if (wsaddrlen < sizeof(win)) return -1;
        win.irdaAddressFamily = WS_AF_IRDA;
        memcpy( win.irdaDeviceID, &uaddr->irda.sir_addr, sizeof(win.irdaDeviceID) );
        if (uaddr->irda.sir_lsap_sel != LSAP_ANY)
            snprintf( win.irdaServiceName, sizeof(win.irdaServiceName), "LSAP-SEL%u", uaddr->irda.sir_lsap_sel );
        else
            memcpy( win.irdaServiceName, uaddr->irda.sir_name, sizeof(win.irdaServiceName) );
        memcpy( wsaddr, &win, sizeof(win) );
        return sizeof(win);
    }
#endif

    case AF_UNSPEC:
        return 0;

    default:
        return -1;

    }
}
562

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
static socklen_t sockaddr_to_unix( const struct WS_sockaddr *wsaddr, int wsaddrlen, union unix_sockaddr *uaddr )
{
    memset( uaddr, 0, sizeof(*uaddr) );

    switch (wsaddr->sa_family)
    {
    case WS_AF_INET:
    {
        struct WS_sockaddr_in win = {0};

        if (wsaddrlen < sizeof(win)) return 0;
        memcpy( &win, wsaddr, sizeof(win) );
        uaddr->in.sin_family = AF_INET;
        uaddr->in.sin_port = win.sin_port;
        memcpy( &uaddr->in.sin_addr, &win.sin_addr, sizeof(win.sin_addr) );
        return sizeof(uaddr->in);
    }

    case WS_AF_INET6:
    {
        struct WS_sockaddr_in6 win = {0};

585 586
        if (wsaddrlen < sizeof(win)) return 0;
        memcpy( &win, wsaddr, sizeof(win) );
587 588 589 590 591
        uaddr->in6.sin6_family = AF_INET6;
        uaddr->in6.sin6_port = win.sin6_port;
        uaddr->in6.sin6_flowinfo = win.sin6_flowinfo;
        memcpy( &uaddr->in6.sin6_addr, &win.sin6_addr, sizeof(win.sin6_addr) );
#ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
592
        uaddr->in6.sin6_scope_id = win.sin6_scope_id;
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
#endif
        return sizeof(uaddr->in6);
    }

#ifdef HAS_IPX
    case WS_AF_IPX:
    {
        struct WS_sockaddr_ipx win = {0};

        if (wsaddrlen < sizeof(win)) return 0;
        memcpy( &win, wsaddr, sizeof(win) );
        uaddr->ipx.sipx_family = AF_IPX;
        memcpy( &uaddr->ipx.sipx_network, win.sa_netnum, sizeof(win.sa_netnum) );
        memcpy( &uaddr->ipx.sipx_node, win.sa_nodenum, sizeof(win.sa_nodenum) );
        uaddr->ipx.sipx_port = win.sa_socket;
        return sizeof(uaddr->ipx);
    }
#endif

#ifdef HAS_IRDA
    case WS_AF_IRDA:
    {
        SOCKADDR_IRDA win = {0};
        unsigned int lsap_sel;

        if (wsaddrlen < sizeof(win)) return 0;
        memcpy( &win, wsaddr, sizeof(win) );
        uaddr->irda.sir_family = AF_IRDA;
        if (sscanf( win.irdaServiceName, "LSAP-SEL%u", &lsap_sel ) == 1)
622
            uaddr->irda.sir_lsap_sel = lsap_sel;
623 624
        else
        {
625
            uaddr->irda.sir_lsap_sel = LSAP_ANY;
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
            memcpy( uaddr->irda.sir_name, win.irdaServiceName, sizeof(win.irdaServiceName) );
        }
        memcpy( &uaddr->irda.sir_addr, win.irdaDeviceID, sizeof(win.irdaDeviceID) );
        return sizeof(uaddr->irda);
    }
#endif

    case WS_AF_UNSPEC:
        switch (wsaddrlen)
        {
        default: /* likely an ipv4 address */
        case sizeof(struct WS_sockaddr_in):
            return sizeof(uaddr->in);

#ifdef HAS_IPX
        case sizeof(struct WS_sockaddr_ipx):
            return sizeof(uaddr->ipx);
#endif

#ifdef HAS_IRDA
        case sizeof(SOCKADDR_IRDA):
            return sizeof(uaddr->irda);
#endif

        case sizeof(struct WS_sockaddr_in6):
            return sizeof(uaddr->in6);
        }

    default:
        return 0;
    }
}

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
static socklen_t get_unix_sockaddr_any( union unix_sockaddr *uaddr, int ws_family )
{
    memset( uaddr, 0, sizeof(*uaddr) );
    switch (ws_family)
    {
        case WS_AF_INET:
            uaddr->in.sin_family = AF_INET;
            return sizeof(uaddr->in);
        case WS_AF_INET6:
            uaddr->in6.sin6_family = AF_INET6;
            return sizeof(uaddr->in6);
#ifdef HAS_IPX
        case WS_AF_IPX:
            uaddr->ipx.sipx_family = AF_IPX;
            return sizeof(uaddr->ipx);
#endif
#ifdef HAS_IRDA
        case WS_AF_IRDA:
            uaddr->irda.sir_family = AF_IRDA;
            return sizeof(uaddr->irda);
#endif
        default:
            return 0;
    }
}

685 686 687 688 689 690 691 692 693
/* some events are generated at the same time but must be sent in a particular
 * order (e.g. CONNECT must be sent before READ) */
static const enum afd_poll_bit event_bitorder[] =
{
    AFD_POLL_BIT_CONNECT,
    AFD_POLL_BIT_CONNECT_ERR,
    AFD_POLL_BIT_ACCEPT,
    AFD_POLL_BIT_OOB,
    AFD_POLL_BIT_READ,
694
    AFD_POLL_BIT_WRITE,
695 696 697
    AFD_POLL_BIT_RESET,
    AFD_POLL_BIT_HUP,
    AFD_POLL_BIT_CLOSE,
698 699
};

700 701 702 703 704 705 706 707
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;

708
static sock_shutdown_t sock_check_pollhup(void)
709 710 711 712 713 714
{
    sock_shutdown_t ret = SOCK_SHUTDOWN_ERROR;
    int fd[2], n;
    struct pollfd pfd;
    char dummy;

715
    if ( socketpair( AF_UNIX, SOCK_STREAM, 0, fd ) ) return ret;
716
    if ( shutdown( fd[0], 1 ) ) goto out;
717 718 719 720 721

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

722 723
    /* Solaris' poll() sometimes returns nothing if given a 0ms timeout here */
    n = poll( &pfd, 1, 1 );
724 725 726 727
    if ( n != 1 ) goto out; /* error or timeout */
    if ( pfd.revents & POLLHUP )
        ret = SOCK_SHUTDOWN_POLLHUP;
    else if ( pfd.revents & POLLIN &&
728
              read( fd[1], &dummy, 1 ) == 0 )
729 730 731
        ret = SOCK_SHUTDOWN_EOF;

out:
732 733
    close( fd[0] );
    close( fd[1] );
734 735 736 737 738
    return ret;
}

void sock_init(void)
{
739
    sock_shutdown_type = sock_check_pollhup();
740 741 742 743

    switch ( sock_shutdown_type )
    {
    case SOCK_SHUTDOWN_EOF:
744
        if (debug_level) fprintf( stderr, "sock_init: shutdown() causes EOF\n" );
745 746
        break;
    case SOCK_SHUTDOWN_POLLHUP:
747
        if (debug_level) fprintf( stderr, "sock_init: shutdown() causes POLLHUP\n" );
748 749
        break;
    default:
750
        fprintf( stderr, "sock_init: ERROR in sock_check_pollhup()\n" );
751 752 753
        sock_shutdown_type = SOCK_SHUTDOWN_EOF;
    }
}
754

755
static void sock_reselect( struct sock *sock )
756
{
757
    int ev = sock_get_poll_events( sock->fd );
758

759
    if (debug_level)
760
        fprintf(stderr,"sock_reselect(%p): new mask %x\n", sock, ev);
761

762
    set_fd_events( sock->fd, ev );
763 764
}

765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
static unsigned int afd_poll_flag_to_win32( unsigned int flags )
{
    static const unsigned int map[] =
    {
        FD_READ,    /* READ */
        FD_OOB,     /* OOB */
        FD_WRITE,   /* WRITE */
        FD_CLOSE,   /* HUP */
        FD_CLOSE,   /* RESET */
        0,          /* CLOSE */
        FD_CONNECT, /* CONNECT */
        FD_ACCEPT,  /* ACCEPT */
        FD_CONNECT, /* CONNECT_ERR */
    };

    unsigned int i, ret = 0;

    for (i = 0; i < ARRAY_SIZE(map); ++i)
    {
        if (flags & (1 << i)) ret |= map[i];
    }

    return ret;
}

790
/* wake anybody waiting on the socket event or send the associated message */
791
static void sock_wake_up( struct sock *sock )
792
{
793
    unsigned int events = sock->pending_events & sock->mask;
794
    int i;
795

796 797 798
    if (sock->event)
    {
        if (debug_level) fprintf(stderr, "signalling events %x ptr %p\n", events, sock->event );
799 800
        if (events)
            set_event( sock->event );
801 802 803
    }
    if (sock->window)
    {
804
        if (debug_level) fprintf(stderr, "signalling events %x win %08x\n", events, sock->window );
805
        for (i = 0; i < ARRAY_SIZE(event_bitorder); i++)
806
        {
807
            enum afd_poll_bit event = event_bitorder[i];
808
            if (events & (1 << event))
809
            {
810
                lparam_t lparam = afd_poll_flag_to_win32(1 << event) | (sock_get_error( sock->errors[event] ) << 16);
811
                post_message( sock->window, sock->message, sock->wparam, lparam );
812 813
            }
        }
814
        sock->pending_events = 0;
815 816
        sock_reselect( sock );
    }
817 818
}

819
static inline int sock_error( struct sock *sock )
820
{
821 822
    int error = 0;
    socklen_t len = sizeof(error);
823

824
    getsockopt( get_unix_fd(sock->fd), SOL_SOCKET, SO_ERROR, (void *)&error, &len);
825 826

    switch (sock->state)
827
    {
828 829 830 831
    case SOCK_UNCONNECTED:
        break;

    case SOCK_CONNECTING:
832 833 834 835
        if (error)
            sock->errors[AFD_POLL_BIT_CONNECT_ERR] = error;
        else
            error = sock->errors[AFD_POLL_BIT_CONNECT_ERR];
836 837 838
        break;

    case SOCK_LISTENING:
839 840 841 842
        if (error)
            sock->errors[AFD_POLL_BIT_ACCEPT] = error;
        else
            error = sock->errors[AFD_POLL_BIT_ACCEPT];
843 844 845 846
        break;

    case SOCK_CONNECTED:
    case SOCK_CONNECTIONLESS:
847 848 849 850 851 852
        if (error == ECONNRESET || error == EPIPE)
        {
            sock->reset = 1;
            error = 0;
        }
        else if (error)
853 854 855 856
            sock->errors[AFD_POLL_BIT_HUP] = error;
        else
            error = sock->errors[AFD_POLL_BIT_HUP];
        break;
857
    }
858

859
    return error;
860 861
}

862
static void free_accept_req( void *private )
863
{
864
    struct accept_req *req = private;
865
    list_remove( &req->entry );
866 867 868 869 870
    if (req->acceptsock)
    {
        req->acceptsock->accept_recv_req = NULL;
        release_object( req->acceptsock );
    }
871
    release_object( req->async );
872
    release_object( req->iosb );
873
    release_object( req->sock );
874 875 876
    free( req );
}

877
static void fill_accept_output( struct accept_req *req )
878
{
879 880
    const data_size_t out_size = req->iosb->out_size;
    struct async *async = req->async;
881 882
    union unix_sockaddr unix_addr;
    struct WS_sockaddr *win_addr;
883
    unsigned int remote_len;
884 885 886 887 888
    socklen_t unix_len;
    int fd, size = 0;
    char *out_data;
    int win_len;

889 890 891 892 893
    if (!(out_data = mem_alloc( out_size )))
    {
        async_terminate( async, get_error() );
        return;
    }
894 895 896 897 898 899 900 901 902 903 904 905

    fd = get_unix_fd( req->acceptsock->fd );

    if (req->recv_len && (size = recv( fd, out_data, req->recv_len, 0 )) < 0)
    {
        if (!req->accepted && errno == EWOULDBLOCK)
        {
            req->accepted = 1;
            sock_reselect( req->acceptsock );
            return;
        }

906
        async_terminate( async, sock_get_ntstatus( errno ) );
907 908 909 910 911 912 913 914
        free( out_data );
        return;
    }

    if (req->local_len)
    {
        if (req->local_len < sizeof(int))
        {
915
            async_terminate( async, STATUS_BUFFER_TOO_SMALL );
916 917 918 919 920 921 922
            free( out_data );
            return;
        }

        unix_len = sizeof(unix_addr);
        win_addr = (struct WS_sockaddr *)(out_data + req->recv_len + sizeof(int));
        if (getsockname( fd, &unix_addr.addr, &unix_len ) < 0 ||
923
            (win_len = sockaddr_from_unix( &unix_addr, win_addr, req->local_len - sizeof(int) )) < 0)
924
        {
925
            async_terminate( async, sock_get_ntstatus( errno ) );
926 927 928 929 930 931 932 933
            free( out_data );
            return;
        }
        memcpy( out_data + req->recv_len, &win_len, sizeof(int) );
    }

    unix_len = sizeof(unix_addr);
    win_addr = (struct WS_sockaddr *)(out_data + req->recv_len + req->local_len + sizeof(int));
934
    remote_len = out_size - req->recv_len - req->local_len;
935
    if (getpeername( fd, &unix_addr.addr, &unix_len ) < 0 ||
936
        (win_len = sockaddr_from_unix( &unix_addr, win_addr, remote_len - sizeof(int) )) < 0)
937
    {
938
        async_terminate( async, sock_get_ntstatus( errno ) );
939 940 941 942 943
        free( out_data );
        return;
    }
    memcpy( out_data + req->recv_len + req->local_len, &win_len, sizeof(int) );

944
    async_request_complete( req->async, STATUS_SUCCESS, size, out_size, out_data );
945 946 947 948 949 950 951 952 953
}

static void complete_async_accept( struct sock *sock, struct accept_req *req )
{
    struct sock *acceptsock = req->acceptsock;
    struct async *async = req->async;

    if (debug_level) fprintf( stderr, "completing accept request for socket %p\n", sock );

954 955
    if (acceptsock)
    {
956 957 958 959 960
        if (!accept_into_socket( sock, acceptsock ))
        {
            async_terminate( async, get_error() );
            return;
        }
961
        fill_accept_output( req );
962 963 964 965 966
    }
    else
    {
        obj_handle_t handle;

967 968 969 970 971
        if (!(acceptsock = accept_socket( sock )))
        {
            async_terminate( async, get_error() );
            return;
        }
972 973 974
        handle = alloc_handle_no_access_check( async_get_thread( async )->process, &acceptsock->obj,
                                               GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, OBJ_INHERIT );
        acceptsock->wparam = handle;
975
        sock_reselect( acceptsock );
976
        release_object( acceptsock );
977 978 979 980 981
        if (!handle)
        {
            async_terminate( async, get_error() );
            return;
        }
982

983
        async_request_complete_alloc( req->async, STATUS_SUCCESS, 0, sizeof(handle), &handle );
984
    }
985 986 987 988 989 990 991 992
}

static void complete_async_accept_recv( struct accept_req *req )
{
    if (debug_level) fprintf( stderr, "completing accept recv request for socket %p\n", req->acceptsock );

    assert( req->recv_len );

993
    fill_accept_output( req );
994 995
}

996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
static void free_connect_req( void *private )
{
    struct connect_req *req = private;

    req->sock->connect_req = NULL;
    release_object( req->async );
    release_object( req->iosb );
    release_object( req->sock );
    free( req );
}

static void complete_async_connect( struct sock *sock )
{
    struct connect_req *req = sock->connect_req;
    const char *in_buffer;
    size_t len;
    int ret;

    if (debug_level) fprintf( stderr, "completing connect request for socket %p\n", sock );

    if (!req->send_len)
    {
1018
        async_terminate( req->async, STATUS_SUCCESS );
1019 1020 1021
        return;
    }

1022
    in_buffer = (const char *)req->iosb->in_data + sizeof(struct afd_connect_params) + req->addr_len;
1023 1024 1025 1026
    len = req->send_len - req->send_cursor;

    ret = send( get_unix_fd( sock->fd ), in_buffer + req->send_cursor, len, 0 );
    if (ret < 0 && errno != EWOULDBLOCK)
1027
        async_terminate( req->async, sock_get_ntstatus( errno ) );
1028
    else if (ret == len)
1029
        async_request_complete( req->async, STATUS_SUCCESS, req->send_len, 0, NULL );
1030 1031 1032 1033
    else
        req->send_cursor += ret;
}

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
static void free_poll_req( void *private )
{
    struct poll_req *req = private;
    unsigned int i;

    if (req->timeout) remove_timeout_user( req->timeout );

    for (i = 0; i < req->count; ++i)
        release_object( req->sockets[i].sock );
    release_object( req->async );
    release_object( req->iosb );
    list_remove( &req->entry );
    free( req );
}

static int is_oobinline( struct sock *sock )
{
    int oobinline;
    socklen_t len = sizeof(oobinline);
    return !getsockopt( get_unix_fd( sock->fd ), SOL_SOCKET, SO_OOBINLINE, (char *)&oobinline, &len ) && oobinline;
}

static int get_poll_flags( struct sock *sock, int event )
{
    int flags = 0;

    /* A connection-mode socket which has never been connected does not return
     * write or hangup events, but Linux reports POLLOUT | POLLHUP. */
1062
    if (sock->state == SOCK_UNCONNECTED)
1063 1064 1065 1066
        event &= ~(POLLOUT | POLLHUP);

    if (event & POLLIN)
    {
1067
        if (sock->state == SOCK_LISTENING)
1068 1069 1070 1071 1072 1073 1074 1075
            flags |= AFD_POLL_ACCEPT;
        else
            flags |= AFD_POLL_READ;
    }
    if (event & POLLPRI)
        flags |= is_oobinline( sock ) ? AFD_POLL_READ : AFD_POLL_OOB;
    if (event & POLLOUT)
        flags |= AFD_POLL_WRITE;
1076
    if (sock->state == SOCK_CONNECTED)
1077 1078 1079 1080 1081
        flags |= AFD_POLL_CONNECT;
    if (event & POLLHUP)
        flags |= AFD_POLL_HUP;
    if (event & POLLERR)
        flags |= AFD_POLL_CONNECT_ERR;
1082 1083
    if (sock->reset)
        flags |= AFD_POLL_RESET;
1084 1085 1086 1087

    return flags;
}

1088 1089
static void complete_async_poll( struct poll_req *req, unsigned int status )
{
1090
    unsigned int i, signaled_count = 0;
1091 1092 1093 1094 1095 1096 1097 1098 1099

    for (i = 0; i < req->count; ++i)
    {
        struct sock *sock = req->sockets[i].sock;

        if (sock->main_poll == req)
            sock->main_poll = NULL;
    }

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    if (!status)
    {
        for (i = 0; i < req->count; ++i)
        {
            if (req->sockets[i].flags)
                ++signaled_count;
        }
    }

    if (is_machine_64bit( async_get_thread( req->async )->process->machine ))
    {
        size_t output_size = offsetof( struct afd_poll_params_64, sockets[signaled_count] );
        struct afd_poll_params_64 *output;

        if (!(output = mem_alloc( output_size )))
        {
            async_terminate( req->async, get_error() );
            return;
        }
        memset( output, 0, output_size );
        output->timeout = req->orig_timeout;
        output->exclusive = req->exclusive;
        for (i = 0; i < req->count; ++i)
        {
            if (!req->sockets[i].flags) continue;
            output->sockets[output->count].socket = req->sockets[i].handle;
            output->sockets[output->count].flags = req->sockets[i].flags;
            output->sockets[output->count].status = req->sockets[i].status;
            ++output->count;
        }
        assert( output->count == signaled_count );

        async_request_complete( req->async, status, output_size, output_size, output );
    }
    else
    {
        size_t output_size = offsetof( struct afd_poll_params_32, sockets[signaled_count] );
        struct afd_poll_params_32 *output;

        if (!(output = mem_alloc( output_size )))
        {
            async_terminate( req->async, get_error() );
            return;
        }
        memset( output, 0, output_size );
        output->timeout = req->orig_timeout;
        output->exclusive = req->exclusive;
        for (i = 0; i < req->count; ++i)
        {
            if (!req->sockets[i].flags) continue;
            output->sockets[output->count].socket = req->sockets[i].handle;
            output->sockets[output->count].flags = req->sockets[i].flags;
            output->sockets[output->count].status = req->sockets[i].status;
            ++output->count;
        }
        assert( output->count == signaled_count );

        async_request_complete( req->async, status, output_size, output_size, output );
    }
1159 1160
}

1161 1162 1163 1164 1165 1166 1167 1168 1169
static void complete_async_polls( struct sock *sock, int event, int error )
{
    int flags = get_poll_flags( sock, event );
    struct poll_req *req, *next;

    LIST_FOR_EACH_ENTRY_SAFE( req, next, &poll_list, struct poll_req, entry )
    {
        unsigned int i;

1170
        if (req->iosb->status != STATUS_PENDING) continue;
1171 1172 1173 1174

        for (i = 0; i < req->count; ++i)
        {
            if (req->sockets[i].sock != sock) continue;
1175
            if (!(req->sockets[i].mask & flags)) continue;
1176 1177 1178

            if (debug_level)
                fprintf( stderr, "completing poll for socket %p, wanted %#x got %#x\n",
1179
                         sock, req->sockets[i].mask, flags );
1180

1181 1182
            req->sockets[i].flags = req->sockets[i].mask & flags;
            req->sockets[i].status = sock_get_ntstatus( error );
1183

1184 1185 1186 1187 1188
            if (req->pending)
            {
                complete_async_poll( req, STATUS_SUCCESS );
                break;
            }
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
        }
    }
}

static void async_poll_timeout( void *private )
{
    struct poll_req *req = private;

    req->timeout = NULL;

1199
    if (req->iosb->status != STATUS_PENDING) return;
1200

1201
    complete_async_poll( req, STATUS_TIMEOUT );
1202 1203
}

1204
static int sock_dispatch_asyncs( struct sock *sock, int event, int error )
1205
{
1206 1207 1208 1209 1210 1211
    if (event & (POLLIN | POLLPRI))
    {
        struct accept_req *req;

        LIST_FOR_EACH_ENTRY( req, &sock->accept_list, struct accept_req, entry )
        {
1212
            if (req->iosb->status == STATUS_PENDING && !req->accepted)
1213 1214
            {
                complete_async_accept( sock, req );
1215
                event &= ~POLLIN;
1216 1217 1218 1219
                break;
            }
        }

1220
        if (sock->accept_recv_req && sock->accept_recv_req->iosb->status == STATUS_PENDING)
1221 1222 1223
            complete_async_accept_recv( sock->accept_recv_req );
    }

1224 1225 1226
    if ((event & POLLOUT) && sock->connect_req && sock->connect_req->iosb->status == STATUS_PENDING)
        complete_async_connect( sock );

1227
    if ((event & (POLLIN | POLLPRI)) && async_queued( &sock->read_q ))
1228
    {
1229 1230 1231 1232 1233
        if (async_waiting( &sock->read_q ))
        {
            if (debug_level) fprintf( stderr, "activating read queue for socket %p\n", sock );
            async_wake_up( &sock->read_q, STATUS_ALERTED );
        }
1234 1235 1236
        event &= ~(POLLIN | POLLPRI);
    }

1237
    if ((event & POLLOUT) && async_queued( &sock->write_q ))
1238
    {
1239 1240 1241 1242 1243
        if (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 );
        }
1244
        event &= ~POLLOUT;
1245
    }
1246

1247 1248 1249 1250 1251
    if (event & (POLLERR | POLLHUP))
    {
        int status = sock_get_ntstatus( error );
        struct accept_req *req, *next;

1252 1253
        async_wake_up( &sock->read_q, status );
        async_wake_up( &sock->write_q, status );
1254 1255

        LIST_FOR_EACH_ENTRY_SAFE( req, next, &sock->accept_list, struct accept_req, entry )
1256 1257 1258 1259
        {
            if (req->iosb->status == STATUS_PENDING)
                async_terminate( req->async, status );
        }
1260

1261
        if (sock->accept_recv_req && sock->accept_recv_req->iosb->status == STATUS_PENDING)
1262
            async_terminate( sock->accept_recv_req->async, status );
1263 1264 1265

        if (sock->connect_req)
            async_terminate( sock->connect_req->async, status );
1266
    }
1267

1268 1269 1270 1271 1272 1273 1274 1275 1276
    if (sock->reset)
    {
        async_wake_up( &sock->read_q, STATUS_CONNECTION_RESET );
        async_wake_up( &sock->write_q, STATUS_CONNECTION_RESET );

        if (sock->accept_recv_req && sock->accept_recv_req->iosb->status == STATUS_PENDING)
            async_terminate( sock->accept_recv_req->async, STATUS_CONNECTION_RESET );
    }

1277
    return event;
1278 1279
}

1280
static void post_socket_event( struct sock *sock, enum afd_poll_bit event_bit )
1281 1282 1283
{
    unsigned int event = (1 << event_bit);

1284 1285 1286 1287 1288
    if (!(sock->reported_events & event))
    {
        sock->pending_events |= event;
        sock->reported_events |= event;
    }
1289 1290
}

1291
static void sock_dispatch_events( struct sock *sock, enum connection_state prevstate, int event )
1292
{
1293
    switch (prevstate)
1294
    {
1295 1296
    case SOCK_UNCONNECTED:
        break;
1297

1298
    case SOCK_CONNECTING:
1299
        if (event & POLLOUT)
1300
        {
1301
            post_socket_event( sock, AFD_POLL_BIT_CONNECT );
1302 1303
            post_socket_event( sock, AFD_POLL_BIT_WRITE );
        }
1304
        if (event & (POLLERR | POLLHUP))
1305
            post_socket_event( sock, AFD_POLL_BIT_CONNECT_ERR );
1306
        break;
1307

1308 1309
    case SOCK_LISTENING:
        if (event & (POLLIN | POLLERR | POLLHUP))
1310
            post_socket_event( sock, AFD_POLL_BIT_ACCEPT );
1311
        break;
1312

1313 1314
    case SOCK_CONNECTED:
    case SOCK_CONNECTIONLESS:
1315 1316 1317
        if (sock->reset)
            post_socket_event( sock, AFD_POLL_BIT_RESET );

1318
        if (event & POLLIN)
1319
            post_socket_event( sock, AFD_POLL_BIT_READ );
1320 1321

        if (event & POLLOUT)
1322
            post_socket_event( sock, AFD_POLL_BIT_WRITE );
1323

1324
        if (event & POLLPRI)
1325
            post_socket_event( sock, AFD_POLL_BIT_OOB );
1326 1327

        if (event & (POLLERR | POLLHUP))
1328
            post_socket_event( sock, AFD_POLL_BIT_HUP );
1329 1330
        break;
    }
1331

1332 1333 1334
    sock_wake_up( sock );
}

1335
static void sock_poll_event( struct fd *fd, int event )
1336
{
1337
    struct sock *sock = get_fd_user( fd );
1338
    int hangup_seen = 0;
1339
    enum connection_state prevstate = sock->state;
1340
    int error = 0;
1341

1342
    assert( sock->obj.ops == &sock_ops );
1343 1344
    grab_object( sock );

1345
    if (debug_level)
1346
        fprintf(stderr, "socket %p select event: %x\n", sock, event);
1347

1348 1349 1350
    if (event & (POLLERR | POLLHUP))
        error = sock_error( sock );

1351
    switch (sock->state)
1352
    {
1353 1354 1355 1356
    case SOCK_UNCONNECTED:
        break;

    case SOCK_CONNECTING:
1357
        if (event & (POLLERR|POLLHUP))
1358
        {
1359
            sock->state = SOCK_UNCONNECTED;
1360
            event &= ~POLLOUT;
1361
        }
1362
        else if (event & POLLOUT)
1363
        {
1364
            sock->state = SOCK_CONNECTED;
1365
            sock->connect_time = current_time;
1366
            sock->errors[AFD_POLL_BIT_CONNECT_ERR] = 0;
1367
        }
1368 1369 1370 1371 1372 1373 1374
        break;

    case SOCK_LISTENING:
        break;

    case SOCK_CONNECTED:
    case SOCK_CONNECTIONLESS:
1375 1376 1377
        if (sock->reset)
            event &= ~(POLLIN | POLLERR | POLLHUP);

1378
        if (sock->type == WS_SOCK_STREAM && (event & POLLIN))
1379
        {
1380
            char dummy;
1381
            int nr;
1382 1383 1384

            /* 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 */
1385
            nr  = recv( get_unix_fd( fd ), &dummy, 1, MSG_PEEK );
1386
            if ( nr == 0 )
1387
            {
1388
                hangup_seen = 1;
1389 1390
                event &= ~POLLIN;
            }
1391
            else if ( nr < 0 )
1392
            {
1393
                event &= ~POLLIN;
1394 1395
                /* EAGAIN can happen if an async recv() falls between the server's poll()
                   call and the invocation of this routine */
1396 1397 1398 1399 1400
                if (errno == ECONNRESET || errno == EPIPE)
                {
                    sock->reset = 1;
                }
                else if (errno != EAGAIN)
1401
                {
1402 1403
                    error = errno;
                    event |= POLLERR;
1404
                    sock->errors[AFD_POLL_BIT_HUP] = error;
1405
                    if ( debug_level )
1406
                        fprintf( stderr, "recv error on socket %p: %d\n", sock, errno );
1407 1408
                }
            }
1409
        }
1410

1411 1412 1413 1414 1415
        if (hangup_seen || (sock_shutdown_type == SOCK_SHUTDOWN_POLLHUP && (event & POLLHUP)))
        {
            sock->hangup = 1;
        }
        else if (event & (POLLHUP | POLLERR))
1416
        {
1417
            sock->aborted = 1;
1418

1419
            if (debug_level)
1420
                fprintf( stderr, "socket %p aborted by error %d, event %#x\n", sock, error, event );
1421 1422
        }

1423 1424
        if (hangup_seen)
            event |= POLLHUP;
1425
        break;
1426
    }
1427

1428
    event = sock_dispatch_asyncs( sock, event, error );
1429
    sock_dispatch_events( sock, prevstate, event );
1430
    complete_async_polls( sock, event, error );
1431

1432
    sock_reselect( sock );
1433
    release_object( sock );
1434 1435 1436 1437 1438 1439
}

static void sock_dump( struct object *obj, int verbose )
{
    struct sock *sock = (struct sock *)obj;
    assert( obj->ops == &sock_ops );
1440
    fprintf( stderr, "Socket fd=%p, state=%x, mask=%x, pending=%x, reported=%x\n",
1441
            sock->fd, sock->state,
1442
            sock->mask, sock->pending_events, sock->reported_events );
1443 1444
}

1445 1446 1447 1448 1449 1450 1451
static int poll_flags_from_afd( struct sock *sock, int flags )
{
    int ev = 0;

    /* A connection-mode socket which has never been connected does
     * not return write or hangup events, but Linux returns
     * POLLOUT | POLLHUP. */
1452
    if (sock->state == SOCK_UNCONNECTED)
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
        return -1;

    if (flags & (AFD_POLL_READ | AFD_POLL_ACCEPT))
        ev |= POLLIN;
    if ((flags & AFD_POLL_HUP) && sock->type == WS_SOCK_STREAM)
        ev |= POLLIN;
    if (flags & AFD_POLL_OOB)
        ev |= is_oobinline( sock ) ? POLLIN : POLLPRI;
    if (flags & AFD_POLL_WRITE)
        ev |= POLLOUT;

    return ev;
}

1467
static int sock_get_poll_events( struct fd *fd )
1468
{
1469
    struct sock *sock = get_fd_user( fd );
1470
    unsigned int mask = sock->mask & ~sock->reported_events;
1471
    struct poll_req *req;
1472 1473
    int ev = 0;

1474
    assert( sock->obj.ops == &sock_ops );
1475

1476 1477 1478
    if (!sock->type) /* not initialized yet */
        return -1;

1479 1480 1481 1482
    LIST_FOR_EACH_ENTRY( req, &poll_list, struct poll_req, entry )
    {
        unsigned int i;

1483 1484
        if (req->iosb->status != STATUS_PENDING) continue;

1485 1486 1487 1488 1489 1490 1491 1492
        for (i = 0; i < req->count; ++i)
        {
            if (req->sockets[i].sock != sock) continue;

            ev |= poll_flags_from_afd( sock, req->sockets[i].mask );
        }
    }

1493 1494 1495 1496 1497 1498 1499
    switch (sock->state)
    {
    case SOCK_UNCONNECTED:
        /* A connection-mode Windows socket which has never been connected does
         * not return any events, but Linux returns POLLOUT | POLLHUP. Hence we
         * need to return -1 here, to prevent the socket from being polled on at
         * all. */
1500 1501
        return -1;

1502
    case SOCK_CONNECTING:
1503 1504
        return POLLOUT;

1505
    case SOCK_LISTENING:
1506
        if (!list_empty( &sock->accept_list ) || (mask & AFD_POLL_ACCEPT))
1507
            ev |= POLLIN;
1508
        break;
1509

1510 1511
    case SOCK_CONNECTED:
    case SOCK_CONNECTIONLESS:
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
        if (sock->hangup && sock->wr_shutdown && !sock->wr_shutdown_pending)
        {
            /* Linux returns POLLHUP if a socket is both SHUT_RD and SHUT_WR, or
             * if both the socket and its peer are SHUT_WR.
             *
             * We don't use SHUT_RD, so we can only encounter this in the latter
             * case. In that case there can't be any pending read requests (they
             * would have already been completed with a length of zero), the
             * above condition ensures that we don't have any pending write
             * requests, and nothing that can change about the socket state that
             * would complete a pending poll request. */
            return -1;
        }

1526
        if (sock->aborted || sock->reset)
1527 1528
            return -1;

1529 1530 1531 1532 1533 1534
        if (sock->accept_recv_req)
        {
            ev |= POLLIN;
        }
        else if (async_queued( &sock->read_q ))
        {
1535 1536 1537 1538 1539 1540 1541 1542 1543
            /* Clear POLLIN and POLLPRI if we have an alerted async, even if
             * we're polling this socket for READ or OOB. We can't signal the
             * poll if the pending async will read all of the data [cf. the
             * matching logic in sock_dispatch_asyncs()], but we also don't
             * want to spin polling for POLLIN if we're not going to use it. */
            if (async_waiting( &sock->read_q ))
                ev |= POLLIN | POLLPRI;
            else
                ev &= ~(POLLIN | POLLPRI);
1544
        }
1545 1546
        else
        {
1547 1548 1549
            /* Don't ask for POLLIN if we got a hangup. We won't receive more
             * data anyway, but we will get POLLIN if SOCK_SHUTDOWN_EOF. */
            if (!sock->hangup)
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
            {
                if (mask & AFD_POLL_READ)
                    ev |= POLLIN;
                if (mask & AFD_POLL_OOB)
                    ev |= POLLPRI;
            }

            /* We use POLLIN with 0 bytes recv() as hangup indication for stream sockets. */
            if (sock->state == SOCK_CONNECTED && (mask & AFD_POLL_HUP) && !(sock->reported_events & AFD_POLL_READ))
                ev |= POLLIN;
        }
1561 1562 1563

        if (async_queued( &sock->write_q ))
        {
1564 1565 1566 1567 1568 1569
            /* As with read asyncs above, clear POLLOUT if we have an alerted
             * async. */
            if (async_waiting( &sock->write_q ))
                ev |= POLLOUT;
            else
                ev &= ~POLLOUT;
1570
        }
1571
        else if (!sock->wr_shutdown && (mask & AFD_POLL_WRITE))
1572 1573 1574 1575 1576
        {
            ev |= POLLOUT;
        }

        break;
1577 1578
    }

1579
    return ev;
1580 1581
}

1582
static enum server_fd_type sock_get_fd_type( struct fd *fd )
1583
{
1584
    return FD_TYPE_SOCKET;
1585 1586
}

1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
static void sock_cancel_async( struct fd *fd, struct async *async )
{
    struct poll_req *req;

    LIST_FOR_EACH_ENTRY( req, &poll_list, struct poll_req, entry )
    {
        unsigned int i;

        if (req->async != async)
            continue;

        for (i = 0; i < req->count; i++)
        {
            struct sock *sock = req->sockets[i].sock;

            if (sock->main_poll == req)
                sock->main_poll = NULL;
        }
    }

    async_terminate( async, STATUS_CANCELLED );
}

1610 1611 1612
static void sock_reselect_async( struct fd *fd, struct async_queue *queue )
{
    struct sock *sock = get_fd_user( fd );
1613

1614
    if (sock->wr_shutdown_pending && list_empty( &sock->write_q.queue ))
1615
    {
1616
        shutdown( get_unix_fd( sock->fd ), SHUT_WR );
1617 1618
        sock->wr_shutdown_pending = 0;
    }
1619

1620 1621 1622 1623
    /* Don't reselect the ifchange queue; we always ask for POLLIN.
     * Don't reselect an uninitialized socket; we can't call set_fd_events() on
     * a pseudo-fd. */
    if (queue != &sock->ifchange_q && sock->type)
1624
        sock_reselect( sock );
1625 1626
}

1627 1628 1629 1630 1631 1632
static struct fd *sock_get_fd( struct object *obj )
{
    struct sock *sock = (struct sock *)obj;
    return (struct fd *)grab_object( sock->fd );
}

1633
static int sock_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1634 1635
{
    struct sock *sock = (struct sock *)obj;
1636

1637 1638
    if (sock->obj.handle_count == 1) /* last handle */
    {
1639 1640 1641
        struct accept_req *accept_req, *accept_next;
        struct poll_req *poll_req, *poll_next;

1642 1643 1644
        if (sock->accept_recv_req)
            async_terminate( sock->accept_recv_req->async, STATUS_CANCELLED );

1645 1646
        LIST_FOR_EACH_ENTRY_SAFE( accept_req, accept_next, &sock->accept_list, struct accept_req, entry )
            async_terminate( accept_req->async, STATUS_CANCELLED );
1647 1648 1649

        if (sock->connect_req)
            async_terminate( sock->connect_req->async, STATUS_CANCELLED );
1650 1651 1652 1653

        LIST_FOR_EACH_ENTRY_SAFE( poll_req, poll_next, &poll_list, struct poll_req, entry )
        {
            struct iosb *iosb = poll_req->iosb;
1654
            BOOL signaled = FALSE;
1655 1656 1657 1658 1659 1660 1661 1662
            unsigned int i;

            if (iosb->status != STATUS_PENDING) continue;

            for (i = 0; i < poll_req->count; ++i)
            {
                if (poll_req->sockets[i].sock == sock)
                {
1663
                    signaled = TRUE;
1664 1665
                    poll_req->sockets[i].flags = AFD_POLL_CLOSE;
                    poll_req->sockets[i].status = 0;
1666 1667 1668
                }
            }

1669
            if (signaled) complete_async_poll( poll_req, STATUS_SUCCESS );
1670
        }
1671
    }
1672
    return async_close_obj_handle( obj, process, handle );
1673 1674 1675 1676 1677
}

static void sock_destroy( struct object *obj )
{
    struct sock *sock = (struct sock *)obj;
1678
    unsigned int i;
1679

1680 1681 1682
    assert( obj->ops == &sock_ops );

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

1684 1685 1686 1687 1688 1689 1690 1691 1692
    for (i = 0; i < 2; ++i)
    {
        if (sock->bound_addr[i] && --sock->bound_addr[i]->reuse_count <= 0)
        {
            rb_remove( &bound_addresses_tree, &sock->bound_addr[i]->entry );
            free( sock->bound_addr[i] );
        }
    }

1693
    if ( sock->deferred )
1694
        release_object( sock->deferred );
1695

1696
    async_wake_up( &sock->ifchange_q, STATUS_CANCELLED );
1697
    sock_release_ifchange( sock );
1698 1699 1700
    free_async_queue( &sock->read_q );
    free_async_queue( &sock->write_q );
    free_async_queue( &sock->ifchange_q );
1701
    free_async_queue( &sock->accept_q );
1702
    free_async_queue( &sock->connect_q );
1703
    free_async_queue( &sock->poll_q );
1704
    if (sock->event) release_object( sock->event );
1705
    if (sock->fd) release_object( sock->fd );
1706 1707
}

1708
static struct sock *create_socket(void)
1709
{
1710 1711 1712 1713
    struct sock *sock;

    if (!(sock = alloc_object( &sock_ops ))) return NULL;
    sock->fd      = NULL;
1714
    sock->state   = SOCK_UNCONNECTED;
1715
    sock->mask    = 0;
1716
    sock->pending_events = 0;
1717
    sock->reported_events = 0;
1718
    sock->proto   = 0;
1719 1720 1721 1722 1723 1724
    sock->type    = 0;
    sock->family  = 0;
    sock->event   = NULL;
    sock->window  = 0;
    sock->message = 0;
    sock->wparam  = 0;
1725
    sock->connect_time = 0;
1726
    sock->deferred = NULL;
1727
    sock->ifchange_obj = NULL;
1728
    sock->accept_recv_req = NULL;
1729
    sock->connect_req = NULL;
1730
    sock->main_poll = NULL;
1731 1732
    memset( &sock->addr, 0, sizeof(sock->addr) );
    sock->addr_len = 0;
1733 1734
    memset( &sock->peer_addr, 0, sizeof(sock->peer_addr) );
    sock->peer_addr_len = 0;
1735 1736
    sock->rd_shutdown = 0;
    sock->wr_shutdown = 0;
1737
    sock->wr_shutdown_pending = 0;
1738
    sock->hangup = 0;
1739
    sock->aborted = 0;
1740
    sock->nonblocking = 0;
1741
    sock->bound = 0;
1742
    sock->reset = 0;
1743
    sock->reuseaddr = 0;
1744
    sock->exclusiveaddruse = 0;
1745
    sock->rcvbuf = 0;
1746
    sock->sndbuf = 0;
1747
    sock->rcvtimeo = 0;
1748
    sock->sndtimeo = 0;
1749
    sock->icmp_fixup_data_len = 0;
1750
    sock->bound_addr[0] = sock->bound_addr[1] = NULL;
1751 1752 1753
    init_async_queue( &sock->read_q );
    init_async_queue( &sock->write_q );
    init_async_queue( &sock->ifchange_q );
1754
    init_async_queue( &sock->accept_q );
1755
    init_async_queue( &sock->connect_q );
1756
    init_async_queue( &sock->poll_q );
1757
    memset( sock->errors, 0, sizeof(sock->errors) );
1758
    list_init( &sock->accept_list );
1759
    return sock;
1760 1761
}

1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
static int get_unix_family( int family )
{
    switch (family)
    {
        case WS_AF_INET: return AF_INET;
        case WS_AF_INET6: return AF_INET6;
#ifdef HAS_IPX
        case WS_AF_IPX: return AF_IPX;
#endif
#ifdef AF_IRDA
        case WS_AF_IRDA: return AF_IRDA;
#endif
        case WS_AF_UNSPEC: return AF_UNSPEC;
        default: return -1;
    }
}

static int get_unix_type( int type )
{
    switch (type)
    {
        case WS_SOCK_DGRAM: return SOCK_DGRAM;
        case WS_SOCK_RAW: return SOCK_RAW;
        case WS_SOCK_STREAM: return SOCK_STREAM;
        default: return -1;
    }
}

static int get_unix_protocol( int protocol )
{
    if (protocol >= WS_NSPROTO_IPX && protocol <= WS_NSPROTO_IPX + 255)
        return protocol;

    switch (protocol)
    {
        case WS_IPPROTO_ICMP: return IPPROTO_ICMP;
        case WS_IPPROTO_IGMP: return IPPROTO_IGMP;
        case WS_IPPROTO_IP: return IPPROTO_IP;
1800
        case WS_IPPROTO_IPV4: return IPPROTO_IPIP;
1801 1802 1803 1804 1805 1806 1807 1808
        case WS_IPPROTO_IPV6: return IPPROTO_IPV6;
        case WS_IPPROTO_RAW: return IPPROTO_RAW;
        case WS_IPPROTO_TCP: return IPPROTO_TCP;
        case WS_IPPROTO_UDP: return IPPROTO_UDP;
        default: return -1;
    }
}

1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
static void set_dont_fragment( int fd, int level, int value )
{
    int optname;

    if (level == IPPROTO_IP)
    {
#ifdef IP_DONTFRAG
        optname = IP_DONTFRAG;
#elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO) && defined(IP_PMTUDISC_DONT)
        optname = IP_MTU_DISCOVER;
        value = value ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
#else
        return;
#endif
    }
    else
    {
#ifdef IPV6_DONTFRAG
        optname = IPV6_DONTFRAG;
#elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
        optname = IPV6_MTU_DISCOVER;
        value = value ? IPV6_PMTUDISC_DO : IPV6_PMTUDISC_DONT;
#else
        return;
#endif
    }

    setsockopt( fd, level, optname, &value, sizeof(value) );
}

1839
static int init_socket( struct sock *sock, int family, int type, int protocol )
1840
{
1841
    unsigned int options = 0;
1842 1843
    int sockfd, unix_type, unix_family, unix_protocol, value;
    socklen_t len;
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864

    unix_family = get_unix_family( family );
    unix_type = get_unix_type( type );
    unix_protocol = get_unix_protocol( protocol );

    if (unix_protocol < 0)
    {
        if (type && unix_type < 0)
            set_win32_error( WSAESOCKTNOSUPPORT );
        else
            set_win32_error( WSAEPROTONOSUPPORT );
        return -1;
    }
    if (unix_family < 0)
    {
        if (family >= 0 && unix_type < 0)
            set_win32_error( WSAESOCKTNOSUPPORT );
        else
            set_win32_error( WSAEAFNOSUPPORT );
        return -1;
    }
1865

1866
    sockfd = socket( unix_family, unix_type, unix_protocol );
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883

#ifdef linux
    if (sockfd == -1 && errno == EPERM && unix_family == AF_INET
        && unix_type == SOCK_RAW && unix_protocol == IPPROTO_ICMP)
    {
        sockfd = socket( unix_family, SOCK_DGRAM, unix_protocol );
        if (sockfd != -1)
        {
            const int val = 1;

            setsockopt( sockfd, IPPROTO_IP, IP_RECVTTL, (const char *)&val, sizeof(val) );
            setsockopt( sockfd, IPPROTO_IP, IP_RECVTOS, (const char *)&val, sizeof(val) );
            setsockopt( sockfd, IPPROTO_IP, IP_PKTINFO, (const char *)&val, sizeof(val) );
        }
    }
#endif

1884 1885
    if (sockfd == -1)
    {
1886 1887
        if (errno == EINVAL) set_win32_error( WSAESOCKTNOSUPPORT );
        else set_win32_error( sock_get_error( errno ));
1888
        return -1;
1889 1890
    }
    fcntl(sockfd, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925

    if (family == WS_AF_IPX && protocol >= WS_NSPROTO_IPX && protocol <= WS_NSPROTO_IPX + 255)
    {
#ifdef HAS_IPX
        int ipx_type = protocol - WS_NSPROTO_IPX;

#ifdef SOL_IPX
        setsockopt( sockfd, SOL_IPX, IPX_TYPE, &ipx_type, sizeof(ipx_type) );
#else
        struct ipx val;
        /* Should we retrieve val using a getsockopt call and then
         * set the modified one? */
        val.ipx_pt = ipx_type;
        setsockopt( sockfd, 0, SO_DEFAULT_HEADERS, &val, sizeof(val) );
#endif
#endif
    }

    if (unix_family == AF_INET || unix_family == AF_INET6)
    {
        /* ensure IP_DONTFRAGMENT is disabled for SOCK_DGRAM and SOCK_RAW, enabled for SOCK_STREAM */
        if (unix_type == SOCK_DGRAM || unix_type == SOCK_RAW) /* in Linux the global default can be enabled */
            set_dont_fragment( sockfd, unix_family == AF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP, FALSE );
        else if (unix_type == SOCK_STREAM)
            set_dont_fragment( sockfd, unix_family == AF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP, TRUE );
    }

#ifdef IPV6_V6ONLY
    if (unix_family == AF_INET6)
    {
        static const int enable = 1;
        setsockopt( sockfd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable) );
    }
#endif

1926 1927
    len = sizeof(value);
    if (!getsockopt( sockfd, SOL_SOCKET, SO_RCVBUF, &value, &len ))
1928 1929 1930 1931 1932 1933
    {
        if (value < MIN_RCVBUF)
        {
            value = MIN_RCVBUF;
            setsockopt( sockfd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value) );
        }
1934
        sock->rcvbuf = value;
1935
    }
1936

1937 1938 1939 1940
    len = sizeof(value);
    if (!getsockopt( sockfd, SOL_SOCKET, SO_SNDBUF, &value, &len ))
        sock->sndbuf = value;

1941
    sock->state  = (type == WS_SOCK_STREAM ? SOCK_UNCONNECTED : SOCK_CONNECTIONLESS);
1942 1943 1944
    sock->proto  = protocol;
    sock->type   = type;
    sock->family = family;
1945

1946 1947
    if (is_tcp_socket( sock ))
    {
1948 1949 1950 1951 1952 1953
        value = 1;
        setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value) );
#ifdef TCP_SYNCNT
        value = 4;
        setsockopt( sockfd, IPPROTO_TCP, TCP_SYNCNT, &value, sizeof(value) );
#endif
1954 1955
    }

1956 1957 1958 1959 1960
    if (sock->fd)
    {
        options = get_fd_options( sock->fd );
        release_object( sock->fd );
    }
1961

1962
    if (!(sock->fd = create_anonymous_fd( &sock_fd_ops, sockfd, &sock->obj, options )))
1963
    {
1964
        return -1;
1965
    }
1966 1967 1968 1969 1970

    /* We can't immediately allow caching for a connection-mode socket, since it
     * might be accepted into (changing the underlying fd object.) */
    if (sock->type != WS_SOCK_STREAM) allow_fd_caching( sock->fd );

1971
    return 0;
1972 1973
}

1974 1975 1976 1977 1978 1979 1980 1981 1982
/* accepts a socket and inits it */
static int accept_new_fd( struct sock *sock )
{

    /* 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.
     */
    struct sockaddr saddr;
1983
    socklen_t slen = sizeof(saddr);
1984 1985 1986 1987
    int acceptfd = accept( get_unix_fd(sock->fd), &saddr, &slen );
    if (acceptfd != -1)
        fcntl( acceptfd, F_SETFL, O_NONBLOCK );
    else
1988
        set_error( sock_get_ntstatus( errno ));
1989 1990 1991
    return acceptfd;
}

1992
/* accept a socket (creates a new fd) */
1993
static struct sock *accept_socket( struct sock *sock )
1994 1995 1996 1997
{
    struct sock *acceptsock;
    int	acceptfd;

1998 1999
    if (get_unix_fd( sock->fd ) == -1) return NULL;

2000 2001
    if ( sock->deferred )
    {
2002 2003
        acceptsock = sock->deferred;
        sock->deferred = NULL;
2004 2005 2006
    }
    else
    {
2007 2008 2009
        union unix_sockaddr unix_addr;
        socklen_t unix_len;

2010
        if ((acceptfd = accept_new_fd( sock )) == -1) return NULL;
2011
        if (!(acceptsock = create_socket()))
2012
        {
2013
            close( acceptfd );
2014 2015
            return NULL;
        }
2016

2017
        /* newly created socket gets the same properties of the listening socket */
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
        acceptsock->state               = SOCK_CONNECTED;
        acceptsock->bound               = 1;
        acceptsock->nonblocking         = sock->nonblocking;
        acceptsock->mask                = sock->mask;
        acceptsock->proto               = sock->proto;
        acceptsock->type                = sock->type;
        acceptsock->family              = sock->family;
        acceptsock->window              = sock->window;
        acceptsock->message             = sock->message;
        acceptsock->reuseaddr           = sock->reuseaddr;
        acceptsock->exclusiveaddruse    = sock->exclusiveaddruse;
2029
        acceptsock->sndbuf              = sock->sndbuf;
2030
        acceptsock->rcvbuf              = sock->rcvbuf;
2031
        acceptsock->sndtimeo            = sock->sndtimeo;
2032
        acceptsock->rcvtimeo            = sock->rcvtimeo;
2033 2034
        acceptsock->connect_time        = current_time;

2035
        if (sock->event) acceptsock->event = (struct event *)grab_object( sock->event );
2036 2037
        if (!(acceptsock->fd = create_anonymous_fd( &sock_fd_ops, acceptfd, &acceptsock->obj,
                                                    get_fd_options( sock->fd ) )))
2038 2039 2040 2041
        {
            release_object( acceptsock );
            return NULL;
        }
2042 2043
        unix_len = sizeof(unix_addr);
        if (!getsockname( acceptfd, &unix_addr.addr, &unix_len ))
2044
        {
2045
            acceptsock->addr_len = sockaddr_from_unix( &unix_addr, &acceptsock->addr.addr, sizeof(acceptsock->addr) );
2046 2047 2048 2049 2050
            if (!getpeername( acceptfd, &unix_addr.addr, &unix_len ))
                acceptsock->peer_addr_len = sockaddr_from_unix( &unix_addr,
                                                                &acceptsock->peer_addr.addr,
                                                                sizeof(acceptsock->peer_addr) );
        }
2051
    }
2052

2053
    clear_error();
2054 2055
    sock->pending_events &= ~AFD_POLL_ACCEPT;
    sock->reported_events &= ~AFD_POLL_ACCEPT;
2056
    sock_reselect( sock );
2057
    return acceptsock;
2058 2059
}

2060 2061
static int accept_into_socket( struct sock *sock, struct sock *acceptsock )
{
2062 2063
    union unix_sockaddr unix_addr;
    socklen_t unix_len;
2064 2065
    int acceptfd;
    struct fd *newfd;
2066 2067 2068

    if (get_unix_fd( sock->fd ) == -1) return FALSE;

2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
    if ( sock->deferred )
    {
        newfd = dup_fd_object( sock->deferred->fd, 0, 0,
                               get_fd_options( acceptsock->fd ) );
        if ( !newfd )
            return FALSE;

        set_fd_user( newfd, &sock_fd_ops, &acceptsock->obj );

        release_object( sock->deferred );
        sock->deferred = NULL;
    }
    else
    {
        if ((acceptfd = accept_new_fd( sock )) == -1)
            return FALSE;

        if (!(newfd = create_anonymous_fd( &sock_fd_ops, acceptfd, &acceptsock->obj,
                                            get_fd_options( acceptsock->fd ) )))
            return FALSE;
    }

2091
    acceptsock->state = SOCK_CONNECTED;
2092
    acceptsock->bound = 1;
2093
    acceptsock->pending_events = 0;
2094
    acceptsock->reported_events = 0;
2095
    acceptsock->proto   = sock->proto;
2096 2097 2098 2099
    acceptsock->type    = sock->type;
    acceptsock->family  = sock->family;
    acceptsock->wparam  = 0;
    acceptsock->deferred = NULL;
2100
    acceptsock->connect_time = current_time;
2101
    fd_copy_completion( acceptsock->fd, newfd );
2102
    release_object( acceptsock->fd );
2103 2104
    acceptsock->fd = newfd;

2105 2106
    unix_len = sizeof(unix_addr);
    if (!getsockname( get_unix_fd( newfd ), &unix_addr.addr, &unix_len ))
2107
    {
2108
        acceptsock->addr_len = sockaddr_from_unix( &unix_addr, &acceptsock->addr.addr, sizeof(acceptsock->addr) );
2109 2110 2111 2112 2113
        if (!getpeername( get_unix_fd( newfd ), &unix_addr.addr, &unix_len ))
            acceptsock->peer_addr_len = sockaddr_from_unix( &unix_addr,
                                                            &acceptsock->peer_addr.addr,
                                                            sizeof(acceptsock->peer_addr) );
    }
2114

2115
    clear_error();
2116 2117
    sock->pending_events &= ~AFD_POLL_ACCEPT;
    sock->reported_events &= ~AFD_POLL_ACCEPT;
2118 2119 2120 2121 2122
    sock_reselect( sock );

    return TRUE;
}

2123 2124
#ifdef IP_BOUND_IF

2125
static int bind_to_iface_name( int fd, in_addr_t bind_addr, const char *name )
2126
{
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
    static const int enable = 1;
    unsigned int index;

    if (!(index = if_nametoindex( name )))
        return -1;

    if (setsockopt( fd, IPPROTO_IP, IP_BOUND_IF, &index, sizeof(index) ))
        return -1;

    return setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable) );
2137 2138
}

2139
#elif defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER) && defined(SO_BINDTODEVICE)
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171

struct interface_filter
{
    struct sock_filter iface_memaddr;
    struct sock_filter iface_rule;
    struct sock_filter ip_memaddr;
    struct sock_filter ip_rule;
    struct sock_filter return_keep;
    struct sock_filter return_dump;
};
# define FILTER_JUMP_DUMP(here)  (u_char)(offsetof(struct interface_filter, return_dump) \
                                 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
                                 /sizeof(struct sock_filter)
# define FILTER_JUMP_KEEP(here)  (u_char)(offsetof(struct interface_filter, return_keep) \
                                 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
                                 /sizeof(struct sock_filter)
# define FILTER_JUMP_NEXT()      (u_char)(0)
# define SKF_NET_DESTIP          16 /* offset in the network header to the destination IP */
static struct interface_filter generic_interface_filter =
{
    /* This filter rule allows incoming packets on the specified interface, which works for all
     * remotely generated packets and for locally generated broadcast packets. */
    BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
    BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
    /* This rule allows locally generated packets targeted at the specific IP address of the chosen
     * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
    BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
    BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
    BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
    BPF_STMT(BPF_RET+BPF_K, 0)          /* dump packet */
};

2172
static int bind_to_iface_name( int fd, in_addr_t bind_addr, const char *name )
2173 2174 2175
{
    struct interface_filter specific_interface_filter;
    struct sock_fprog filter_prog;
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
    static const int enable = 1;
    unsigned int index;
    in_addr_t ifindex;

    if (!setsockopt( fd, SOL_SOCKET, SO_BINDTODEVICE, name, strlen( name ) + 1 ))
        return 0;

    /* SO_BINDTODEVICE requires NET_CAP_RAW until Linux 5.7. */
    if (debug_level)
        fprintf( stderr, "setsockopt SO_BINDTODEVICE fd %d, name %s failed: %s, falling back to SO_REUSE_ADDR\n",
                 fd, name, strerror( errno ));

    if (!(index = if_nametoindex( name )))
        return -1;
2190

2191 2192 2193
    ifindex = htonl( index );
    if (setsockopt( fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex) ) < 0)
        return -1;
2194 2195 2196 2197 2198 2199

    specific_interface_filter = generic_interface_filter;
    specific_interface_filter.iface_rule.k = index;
    specific_interface_filter.ip_rule.k = htonl( bind_addr );
    filter_prog.len = sizeof(generic_interface_filter) / sizeof(struct sock_filter);
    filter_prog.filter = (struct sock_filter *)&specific_interface_filter;
2200 2201 2202 2203
    if (setsockopt( fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog) ))
        return -1;

    return setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable) );
2204 2205 2206 2207
}

#else

2208
static int bind_to_iface_name( int fd, in_addr_t bind_addr, const char *name )
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
{
    errno = EOPNOTSUPP;
    return -1;
}

#endif /* LINUX_BOUND_IF */

/* Take bind() calls on any name corresponding to a local network adapter and
 * restrict the given socket to operating only on the specified interface. This
 * restriction consists of two components:
 *  1) An outgoing packet restriction suggesting the egress interface for all
 *     packets.
 *  2) An incoming packet restriction dropping packets not meant for the
 *     interface.
 * If the function succeeds in placing these restrictions, then the name for the
 * bind() may safely be changed to INADDR_ANY, permitting the transmission and
 * receipt of broadcast packets on the socket. This behavior is only relevant to
 * UDP sockets and is needed for applications that expect to be able to receive
 * broadcast packets on a socket that is bound to a specific network interface.
 */
static int bind_to_interface( struct sock *sock, const struct sockaddr_in *addr )
{
    in_addr_t bind_addr = addr->sin_addr.s_addr;
    struct ifaddrs *ifaddrs, *ifaddr;
    int fd = get_unix_fd( sock->fd );
2234
    int err = 0;
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247

    if (bind_addr == htonl( INADDR_ANY ) || bind_addr == htonl( INADDR_LOOPBACK ))
        return 0;
    if (sock->type != WS_SOCK_DGRAM)
        return 0;

    if (getifaddrs( &ifaddrs ) < 0) return 0;

    for (ifaddr = ifaddrs; ifaddr != NULL; ifaddr = ifaddr->ifa_next)
    {
        if (ifaddr->ifa_addr && ifaddr->ifa_addr->sa_family == AF_INET
                && ((struct sockaddr_in *)ifaddr->ifa_addr)->sin_addr.s_addr == bind_addr)
        {
2248
            if ((err = bind_to_iface_name( fd, bind_addr, ifaddr->ifa_name )) < 0)
2249 2250 2251 2252
            {
                if (debug_level)
                    fprintf( stderr, "failed to bind to interface: %s\n", strerror( errno ) );
            }
2253
            break;
2254 2255
        }
    }
2256
    freeifaddrs( ifaddrs );
2257
    return !err;
2258 2259
}

2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
#ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
static unsigned int get_ipv6_interface_index( const struct in6_addr *addr )
{
    struct ifaddrs *ifaddrs, *ifaddr;

    if (getifaddrs( &ifaddrs ) < 0) return 0;

    for (ifaddr = ifaddrs; ifaddr != NULL; ifaddr = ifaddr->ifa_next)
    {
        if (ifaddr->ifa_addr && ifaddr->ifa_addr->sa_family == AF_INET6
                && !memcmp( &((struct sockaddr_in6 *)ifaddr->ifa_addr)->sin6_addr, addr, sizeof(*addr) ))
        {
            unsigned int index = if_nametoindex( ifaddr->ifa_name );

            if (!index)
            {
                if (debug_level)
                    fprintf( stderr, "Unable to look up interface index for %s: %s\n",
                             ifaddr->ifa_name, strerror( errno ) );
                continue;
            }

            freeifaddrs( ifaddrs );
            return index;
        }
    }

    freeifaddrs( ifaddrs );
    return 0;
}
#endif

Bruno Jesus's avatar
Bruno Jesus committed
2292
/* return an errno value mapped to a WSA error */
2293
static unsigned int sock_get_error( int err )
2294
{
2295
    switch (err)
2296
    {
2297 2298
        case EINTR:             return WSAEINTR;
        case EBADF:             return WSAEBADF;
2299
        case EPERM:
2300 2301 2302 2303
        case EACCES:            return WSAEACCES;
        case EFAULT:            return WSAEFAULT;
        case EINVAL:            return WSAEINVAL;
        case EMFILE:            return WSAEMFILE;
2304
        case EINPROGRESS:
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
        case EWOULDBLOCK:       return WSAEWOULDBLOCK;
        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;
2323
        case EPIPE:
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
        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;
2337
#ifdef EPROCLIM
2338
        case EPROCLIM:          return WSAEPROCLIM;
2339 2340
#endif
#ifdef EUSERS
2341
        case EUSERS:            return WSAEUSERS;
2342 2343
#endif
#ifdef EDQUOT
2344
        case EDQUOT:            return WSAEDQUOT;
2345 2346
#endif
#ifdef ESTALE
2347
        case ESTALE:            return WSAESTALE;
2348 2349
#endif
#ifdef EREMOTE
2350
        case EREMOTE:           return WSAEREMOTE;
2351
#endif
2352 2353

        case 0:                 return 0;
2354 2355 2356 2357
        default:
            errno = err;
            perror("wineserver: sock_get_error() can't map error");
            return WSAEFAULT;
2358 2359 2360
    }
}

2361 2362 2363 2364 2365 2366 2367 2368
static int sock_get_ntstatus( int err )
{
    switch ( err )
    {
        case EBADF:             return STATUS_INVALID_HANDLE;
        case EBUSY:             return STATUS_DEVICE_BUSY;
        case EPERM:
        case EACCES:            return STATUS_ACCESS_DENIED;
2369
        case EFAULT:            return STATUS_ACCESS_VIOLATION;
2370 2371 2372
        case EINVAL:            return STATUS_INVALID_PARAMETER;
        case ENFILE:
        case EMFILE:            return STATUS_TOO_MANY_OPENED_FILES;
2373
        case EINPROGRESS:
2374
        case EWOULDBLOCK:       return STATUS_DEVICE_NOT_READY;
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
        case EALREADY:          return STATUS_NETWORK_BUSY;
        case ENOTSOCK:          return STATUS_OBJECT_TYPE_MISMATCH;
        case EDESTADDRREQ:      return STATUS_INVALID_PARAMETER;
        case EMSGSIZE:          return STATUS_BUFFER_OVERFLOW;
        case EPROTONOSUPPORT:
        case ESOCKTNOSUPPORT:
        case EPFNOSUPPORT:
        case EAFNOSUPPORT:
        case EPROTOTYPE:        return STATUS_NOT_SUPPORTED;
        case ENOPROTOOPT:       return STATUS_INVALID_PARAMETER;
        case EOPNOTSUPP:        return STATUS_NOT_SUPPORTED;
2386
        case EADDRINUSE:        return STATUS_SHARING_VIOLATION;
2387 2388 2389
        /* Linux returns ENODEV when specifying an invalid sin6_scope_id;
         * Windows returns STATUS_INVALID_ADDRESS_COMPONENT */
        case ENODEV:
2390
        case EADDRNOTAVAIL:     return STATUS_INVALID_ADDRESS_COMPONENT;
2391 2392
        case ECONNREFUSED:      return STATUS_CONNECTION_REFUSED;
        case ESHUTDOWN:         return STATUS_PIPE_DISCONNECTED;
2393
        case ENOTCONN:          return STATUS_INVALID_CONNECTION;
2394 2395
        case ETIMEDOUT:         return STATUS_IO_TIMEOUT;
        case ENETUNREACH:       return STATUS_NETWORK_UNREACHABLE;
2396
        case EHOSTUNREACH:      return STATUS_HOST_UNREACHABLE;
2397 2398 2399 2400
        case ENETDOWN:          return STATUS_NETWORK_BUSY;
        case EPIPE:
        case ECONNRESET:        return STATUS_CONNECTION_RESET;
        case ECONNABORTED:      return STATUS_CONNECTION_ABORTED;
2401
        case EISCONN:           return STATUS_CONNECTION_ACTIVE;
2402 2403 2404 2405 2406 2407 2408 2409 2410

        case 0:                 return STATUS_SUCCESS;
        default:
            errno = err;
            perror("wineserver: sock_get_ntstatus() can't map error");
            return STATUS_UNSUCCESSFUL;
    }
}

2411
static struct accept_req *alloc_accept_req( struct sock *sock, struct sock *acceptsock, struct async *async,
2412 2413 2414 2415 2416 2417 2418
                                            const struct afd_accept_into_params *params )
{
    struct accept_req *req = mem_alloc( sizeof(*req) );

    if (req)
    {
        req->async = (struct async *)grab_object( async );
2419
        req->iosb = async_get_iosb( async );
2420
        req->sock = (struct sock *)grab_object( sock );
2421
        req->acceptsock = acceptsock;
2422
        if (acceptsock) grab_object( acceptsock );
2423 2424 2425
        req->accepted = 0;
        req->recv_len = 0;
        req->local_len = 0;
2426 2427 2428 2429 2430
        if (params)
        {
            req->recv_len = params->recv_len;
            req->local_len = params->local_len;
        }
2431 2432 2433 2434
    }
    return req;
}

2435
static void sock_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2436 2437
{
    struct sock *sock = get_fd_user( fd );
2438
    int unix_fd = -1;
2439 2440 2441

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

2442 2443
    if (code != IOCTL_AFD_WINE_CREATE && code != IOCTL_AFD_POLL && (unix_fd = get_unix_fd( fd )) < 0)
        return;
2444 2445 2446

    switch(code)
    {
2447
    case IOCTL_AFD_WINE_CREATE:
2448 2449 2450 2451 2452 2453
    {
        const struct afd_create_params *params = get_req_data();

        if (get_req_data_size() != sizeof(*params))
        {
            set_error( STATUS_INVALID_PARAMETER );
2454
            return;
2455
        }
2456
        init_socket( sock, params->family, params->type, params->protocol );
2457
        return;
2458 2459
    }

2460
    case IOCTL_AFD_WINE_ACCEPT:
2461 2462 2463 2464 2465 2466 2467
    {
        struct sock *acceptsock;
        obj_handle_t handle;

        if (get_reply_max_size() != sizeof(handle))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
2468
            return;
2469 2470
        }

2471 2472 2473 2474
        if (!(acceptsock = accept_socket( sock )))
        {
            struct accept_req *req;

2475 2476
            if (sock->nonblocking) return;
            if (get_error() != STATUS_DEVICE_NOT_READY) return;
2477

2478
            if (!(req = alloc_accept_req( sock, NULL, async, NULL ))) return;
2479 2480
            list_add_tail( &sock->accept_list, &req->entry );

2481
            async_set_completion_callback( async, free_accept_req, req );
2482 2483 2484
            queue_async( &sock->accept_q, async );
            sock_reselect( sock );
            set_error( STATUS_PENDING );
2485
            return;
2486
        }
2487 2488 2489
        handle = alloc_handle( current->process, &acceptsock->obj,
                               GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, OBJ_INHERIT );
        acceptsock->wparam = handle;
2490
        sock_reselect( acceptsock );
2491 2492
        release_object( acceptsock );
        set_reply_data( &handle, sizeof(handle) );
2493
        return;
2494 2495
    }

2496
    case IOCTL_AFD_WINE_ACCEPT_INTO:
2497 2498
    {
        static const int access = FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | FILE_READ_DATA;
2499
        const struct afd_accept_into_params *params = get_req_data();
2500
        struct sock *acceptsock;
2501 2502
        unsigned int remote_len;
        struct accept_req *req;
2503

2504 2505 2506
        if (get_req_data_size() != sizeof(*params) ||
            get_reply_max_size() < params->recv_len ||
            get_reply_max_size() - params->recv_len < params->local_len)
2507 2508
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
2509
            return;
2510 2511
        }

2512 2513 2514 2515
        remote_len = get_reply_max_size() - params->recv_len - params->local_len;
        if (remote_len < sizeof(int))
        {
            set_error( STATUS_INVALID_PARAMETER );
2516
            return;
2517 2518 2519
        }

        if (!(acceptsock = (struct sock *)get_handle_obj( current->process, params->accept_handle, access, &sock_ops )))
2520
            return;
2521

2522 2523 2524
        if (acceptsock->accept_recv_req)
        {
            release_object( acceptsock );
2525
            set_error( STATUS_INVALID_PARAMETER );
2526
            return;
2527 2528
        }

2529
        if (!(req = alloc_accept_req( sock, acceptsock, async, params )))
2530 2531
        {
            release_object( acceptsock );
2532
            return;
2533
        }
2534 2535
        list_add_tail( &sock->accept_list, &req->entry );
        acceptsock->accept_recv_req = req;
2536
        release_object( acceptsock );
2537 2538

        acceptsock->wparam = params->accept_handle;
2539
        async_set_completion_callback( async, free_accept_req, req );
2540 2541 2542
        queue_async( &sock->accept_q, async );
        sock_reselect( sock );
        set_error( STATUS_PENDING );
2543
        return;
2544 2545
    }

2546 2547 2548 2549 2550 2551 2552
    case IOCTL_AFD_LISTEN:
    {
        const struct afd_listen_params *params = get_req_data();

        if (get_req_data_size() < sizeof(*params))
        {
            set_error( STATUS_INVALID_PARAMETER );
2553
            return;
2554 2555
        }

2556 2557 2558 2559 2560 2561
        if (sock->type == WS_SOCK_DGRAM)
        {
            set_error( STATUS_NOT_SUPPORTED );
            return;
        }

2562 2563 2564
        if (!sock->bound)
        {
            set_error( STATUS_INVALID_PARAMETER );
2565
            return;
2566 2567
        }

2568 2569 2570
        if (listen( unix_fd, params->backlog ) < 0)
        {
            set_error( sock_get_ntstatus( errno ) );
2571
            return;
2572 2573
        }

2574
        sock->state = SOCK_LISTENING;
2575

2576 2577 2578
        /* a listening socket can no longer be accepted into */
        allow_fd_caching( sock->fd );

2579
        /* we may already be selecting for AFD_POLL_ACCEPT */
2580
        sock_reselect( sock );
2581
        return;
2582 2583
    }

2584 2585 2586
    case IOCTL_AFD_WINE_CONNECT:
    {
        const struct afd_connect_params *params = get_req_data();
2587
        const struct WS_sockaddr *addr;
2588
        union unix_sockaddr unix_addr, peer_addr;
2589
        struct connect_req *req;
2590
        socklen_t unix_len;
2591 2592 2593 2594 2595 2596
        int send_len, ret;

        if (get_req_data_size() < sizeof(*params) ||
            get_req_data_size() - sizeof(*params) < params->addr_len)
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
2597
            return;
2598 2599
        }
        send_len = get_req_data_size() - sizeof(*params) - params->addr_len;
2600
        addr = (const struct WS_sockaddr *)(params + 1);
2601

2602 2603 2604
        if (!params->synchronous && !sock->bound)
        {
            set_error( STATUS_INVALID_PARAMETER );
2605
            return;
2606 2607
        }

2608 2609 2610
        if (sock->accept_recv_req)
        {
            set_error( STATUS_INVALID_PARAMETER );
2611
            return;
2612 2613 2614 2615
        }

        if (sock->connect_req)
        {
2616
            set_error( STATUS_INVALID_PARAMETER );
2617
            return;
2618 2619
        }

2620
        switch (sock->state)
2621
        {
2622 2623
            case SOCK_LISTENING:
                set_error( STATUS_INVALID_PARAMETER );
2624
                return;
2625 2626 2627 2628 2629

            case SOCK_CONNECTING:
                /* FIXME: STATUS_ADDRESS_ALREADY_ASSOCIATED probably isn't right,
                 * but there's no status code that maps to WSAEALREADY... */
                set_error( params->synchronous ? STATUS_ADDRESS_ALREADY_ASSOCIATED : STATUS_INVALID_PARAMETER );
2630
                return;
2631 2632 2633

            case SOCK_CONNECTED:
                set_error( STATUS_CONNECTION_ACTIVE );
2634
                return;
2635 2636 2637 2638

            case SOCK_UNCONNECTED:
            case SOCK_CONNECTIONLESS:
                break;
2639 2640
        }

2641 2642 2643 2644
        unix_len = sockaddr_to_unix( addr, params->addr_len, &unix_addr );
        if (!unix_len)
        {
            set_error( STATUS_INVALID_ADDRESS );
2645
            return;
2646 2647 2648 2649
        }
        if (unix_addr.addr.sa_family == AF_INET && !memcmp( &unix_addr.in.sin_addr, magic_loopback_addr, 4 ))
            unix_addr.in.sin_addr.s_addr = htonl( INADDR_LOOPBACK );

2650
        memcpy( &peer_addr, &unix_addr, sizeof(unix_addr) );
2651
        ret = connect( unix_fd, &unix_addr.addr, unix_len );
2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
        if (ret < 0 && errno == ECONNABORTED)
        {
            /* On Linux with nonblocking socket if the previous connect() failed for any reason (including
             * timeout), next connect will fail. If the error code was queried by getsockopt( SO_ERROR )
             * the error code returned now is ECONNABORTED (otherwise that is the actual connect() failure
             * error code). If we got here after previous connect attempt on the socket that means
             * we already queried SO_ERROR in sock_error(), so retrying on ECONNABORTED only is
             * sufficient. */
            ret = connect( unix_fd, &unix_addr.addr, unix_len );
        }

2663 2664 2665
        if (ret < 0 && errno != EINPROGRESS)
        {
            set_error( sock_get_ntstatus( errno ) );
2666
            return;
2667 2668
        }

2669 2670 2671
        /* a connected or connecting socket can no longer be accepted into */
        allow_fd_caching( sock->fd );

2672
        unix_len = sizeof(unix_addr);
2673 2674 2675 2676
        getsockname( unix_fd, &unix_addr.addr, &unix_len );
        sock->addr_len = sockaddr_from_unix( &unix_addr, &sock->addr.addr, sizeof(sock->addr) );
        sock->peer_addr_len = sockaddr_from_unix( &peer_addr, &sock->peer_addr.addr, sizeof(sock->peer_addr));

2677 2678
        sock->bound = 1;

2679 2680
        if (!ret)
        {
2681 2682 2683 2684 2685
            if (sock->type != WS_SOCK_DGRAM)
            {
                sock->state = SOCK_CONNECTED;
                sock->connect_time = current_time;
            }
2686

2687
            if (!send_len) return;
2688 2689
        }

2690 2691
        if (sock->type != WS_SOCK_DGRAM)
            sock->state = SOCK_CONNECTING;
2692

2693
        if (params->synchronous && sock->nonblocking)
2694 2695 2696
        {
            sock_reselect( sock );
            set_error( STATUS_DEVICE_NOT_READY );
2697
            return;
2698 2699
        }

2700 2701 2702
        if (!(req = mem_alloc( sizeof(*req) )))
            return;

2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714
        req->async = (struct async *)grab_object( async );
        req->iosb = async_get_iosb( async );
        req->sock = (struct sock *)grab_object( sock );
        req->addr_len = params->addr_len;
        req->send_len = send_len;
        req->send_cursor = 0;

        async_set_completion_callback( async, free_connect_req, req );
        sock->connect_req = req;
        queue_async( &sock->connect_q, async );
        sock_reselect( sock );
        set_error( STATUS_PENDING );
2715
        return;
2716 2717
    }

2718 2719 2720 2721 2722 2723 2724
    case IOCTL_AFD_WINE_SHUTDOWN:
    {
        unsigned int how;

        if (get_req_data_size() < sizeof(int))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
2725
            return;
2726 2727 2728 2729 2730 2731
        }
        how = *(int *)get_req_data();

        if (how > SD_BOTH)
        {
            set_error( STATUS_INVALID_PARAMETER );
2732
            return;
2733 2734
        }

2735
        if (sock->state != SOCK_CONNECTED && sock->state != SOCK_CONNECTIONLESS)
2736 2737
        {
            set_error( STATUS_INVALID_CONNECTION );
2738
            return;
2739 2740 2741 2742
        }

        if (how != SD_SEND)
        {
2743
            sock->rd_shutdown = 1;
2744 2745 2746
        }
        if (how != SD_RECEIVE)
        {
2747
            sock->wr_shutdown = 1;
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
            if (list_empty( &sock->write_q.queue ))
                shutdown( unix_fd, SHUT_WR );
            else
                sock->wr_shutdown_pending = 1;
        }

        if (how == SD_BOTH)
        {
            if (sock->event) release_object( sock->event );
            sock->event = NULL;
            sock->window = 0;
            sock->mask = 0;
2760
            sock->nonblocking = 1;
2761 2762 2763
        }

        sock_reselect( sock );
2764
        return;
2765 2766
    }

2767
    case IOCTL_AFD_WINE_ADDRESS_LIST_CHANGE:
2768 2769 2770 2771 2772 2773
    {
        int force_async;

        if (get_req_data_size() < sizeof(int))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
2774
            return;
2775 2776 2777
        }
        force_async = *(int *)get_req_data();

2778
        if (sock->nonblocking && !force_async)
2779
        {
2780
            set_error( STATUS_DEVICE_NOT_READY );
2781
            return;
2782
        }
2783
        if (!sock_get_ifchange( sock )) return;
2784 2785
        queue_async( &sock->ifchange_q, async );
        set_error( STATUS_PENDING );
2786
        return;
2787
    }
2788

2789 2790 2791 2792
    case IOCTL_AFD_WINE_FIONBIO:
        if (get_req_data_size() < sizeof(int))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
2793
            return;
2794 2795 2796
        }
        if (*(int *)get_req_data())
        {
2797
            sock->nonblocking = 1;
2798 2799 2800 2801 2802 2803
        }
        else
        {
            if (sock->mask)
            {
                set_error( STATUS_INVALID_PARAMETER );
2804
                return;
2805
            }
2806
            sock->nonblocking = 0;
2807
        }
2808
        return;
2809

2810 2811 2812 2813 2814 2815
    case IOCTL_AFD_EVENT_SELECT:
    {
        struct event *event = NULL;
        obj_handle_t event_handle;
        int mask;

2816
        set_async_pending( async );
2817

2818 2819 2820 2821
        if (is_machine_64bit( current->process->machine ))
        {
            const struct afd_event_select_params_64 *params = get_req_data();

2822
            if (get_req_data_size() < sizeof(*params))
2823 2824
            {
                set_error( STATUS_INVALID_PARAMETER );
2825
                return;
2826 2827 2828 2829 2830 2831 2832 2833 2834
            }

            event_handle = params->event;
            mask = params->mask;
        }
        else
        {
            const struct afd_event_select_params_32 *params = get_req_data();

2835
            if (get_req_data_size() < sizeof(*params))
2836 2837
            {
                set_error( STATUS_INVALID_PARAMETER );
2838
                return;
2839 2840 2841 2842 2843 2844 2845 2846 2847 2848
            }

            event_handle = params->event;
            mask = params->mask;
        }

        if ((event_handle || mask) &&
            !(event = get_event_obj( current->process, event_handle, EVENT_MODIFY_STATE )))
        {
            set_error( STATUS_INVALID_PARAMETER );
2849
            return;
2850 2851 2852 2853 2854 2855 2856 2857 2858
        }

        if (sock->event) release_object( sock->event );
        sock->event = event;
        sock->mask = mask;
        sock->window = 0;
        sock->message = 0;
        sock->wparam = 0;
        sock->nonblocking = 1;
2859 2860

        sock_reselect( sock );
2861 2862 2863 2864 2865
        /* Explicitly wake the socket up if the mask causes it to become
         * signaled. Note that reselecting isn't enough, since we might already
         * have had events recorded in sock->reported_events and we don't want
         * to select for them again. */
        sock_wake_up( sock );
2866

2867
        return;
2868 2869 2870 2871 2872 2873 2874 2875 2876
    }

    case IOCTL_AFD_WINE_MESSAGE_SELECT:
    {
        const struct afd_message_select_params *params = get_req_data();

        if (get_req_data_size() < sizeof(params))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
2877
            return;
2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
        }

        if (sock->event) release_object( sock->event );

        if (params->window)
        {
            sock->pending_events = 0;
            sock->reported_events = 0;
        }
        sock->event = NULL;
        sock->mask = params->mask;
        sock->window = params->window;
        sock->message = params->message;
        sock->wparam = params->handle;
        sock->nonblocking = 1;
2893 2894 2895

        sock_reselect( sock );

2896
        return;
2897 2898
    }

2899 2900 2901
    case IOCTL_AFD_BIND:
    {
        const struct afd_bind_params *params = get_req_data();
2902
        union unix_sockaddr unix_addr, bind_addr;
2903 2904
        data_size_t in_size;
        socklen_t unix_len;
2905
        int v6only = 1;
2906 2907 2908 2909 2910 2911

        /* the ioctl is METHOD_NEITHER, so ntdll gives us the output buffer as
         * input */
        if (get_req_data_size() < get_reply_max_size())
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
2912
            return;
2913 2914 2915
        }
        in_size = get_req_data_size() - get_reply_max_size();
        if (in_size < offsetof(struct afd_bind_params, addr.sa_data)
2916
                || get_reply_max_size() < in_size - sizeof(int))
2917 2918
        {
            set_error( STATUS_INVALID_PARAMETER );
2919
            return;
2920 2921
        }

2922 2923 2924
        if (sock->bound)
        {
            set_error( STATUS_ADDRESS_ALREADY_ASSOCIATED );
2925
            return;
2926 2927
        }

2928 2929 2930 2931
        unix_len = sockaddr_to_unix( &params->addr, in_size - sizeof(int), &unix_addr );
        if (!unix_len)
        {
            set_error( STATUS_INVALID_ADDRESS );
2932
            return;
2933
        }
2934
        bind_addr = unix_addr;
2935

2936
        if (unix_addr.addr.sa_family == AF_INET)
2937 2938 2939
        {
            if (!memcmp( &unix_addr.in.sin_addr, magic_loopback_addr, 4 )
                    || bind_to_interface( sock, &unix_addr.in ))
2940
                bind_addr.in.sin_addr.s_addr = htonl( INADDR_ANY );
2941
        }
2942 2943 2944 2945 2946 2947 2948 2949 2950 2951
        else if (unix_addr.addr.sa_family == AF_INET6)
        {
#ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
            /* Windows allows specifying zero to use the default scope. Linux
             * interprets it as an interface index and requires that it be
             * nonzero. */
            if (!unix_addr.in6.sin6_scope_id)
                bind_addr.in6.sin6_scope_id = get_ipv6_interface_index( &unix_addr.in6.sin6_addr );
#endif
        }
2952

2953
        set_async_pending( async );
2954

2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
#ifdef IPV6_V6ONLY
    if (sock->family == WS_AF_INET6)
    {
        socklen_t len = sizeof(v6only);

        getsockopt( get_unix_fd(sock->fd), IPPROTO_IPV6, IPV6_V6ONLY, &v6only, &len );
    }
#endif

        if (check_addr_usage( sock, &bind_addr, v6only ))
            return;

2967
        if (bind( unix_fd, &bind_addr.addr, unix_len ) < 0)
2968
        {
2969 2970
            if (errno == EADDRINUSE && sock->reuseaddr)
                errno = EACCES;
2971 2972

            set_error( sock_get_ntstatus( errno ) );
2973
            return;
2974
        }
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987

        sock->bound = 1;

        unix_len = sizeof(bind_addr);
        if (!getsockname( unix_fd, &bind_addr.addr, &unix_len ))
        {
            /* store the interface or magic loopback address instead of the
             * actual unix address */
            if (bind_addr.addr.sa_family == AF_INET)
                bind_addr.in.sin_addr = unix_addr.in.sin_addr;
            sock->addr_len = sockaddr_from_unix( &bind_addr, &sock->addr.addr, sizeof(sock->addr) );
        }

2988 2989
        update_addr_usage( sock, &bind_addr, v6only );

2990 2991
        if (get_reply_max_size() >= sock->addr_len)
            set_reply_data( &sock->addr, sock->addr_len );
2992
        return;
2993 2994
    }

2995 2996 2997 2998
    case IOCTL_AFD_GETSOCKNAME:
        if (!sock->bound)
        {
            set_error( STATUS_INVALID_PARAMETER );
2999
            return;
3000 3001 3002 3003 3004
        }

        if (get_reply_max_size() < sock->addr_len)
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3005
            return;
3006 3007 3008
        }

        set_reply_data( &sock->addr, sock->addr_len );
3009
        return;
3010

3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045
    case IOCTL_AFD_WINE_GETPEERNAME:
        if (sock->state != SOCK_CONNECTED &&
            sock->state != SOCK_CONNECTING &&
            sock->state != SOCK_CONNECTIONLESS)
        {
            set_error( STATUS_INVALID_CONNECTION );
            return;
        }

        /* If ConnectEx() hasn't finished connecting (or failing to connect) the provided
         * socket, getpeername() can't be called on it. This seems to be undocumented
         * and is *not* the case for connect(), but we do test for it in ws2_32.
         * connect_req is non-NULL iff ConnectEx() was used and has not finished,
         * so we can use it as a check for ConnectEx() usage here. */
        if (sock->connect_req)
        {
            set_error( STATUS_INVALID_CONNECTION );
            return;
        }

        if (!sock->peer_addr_len && sock->type == WS_SOCK_DGRAM)
        {
            set_error( STATUS_INVALID_CONNECTION );
            return;
        }

        if (get_reply_max_size() < sock->peer_addr_len)
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
            return;
        }

        set_reply_data( &sock->peer_addr, sock->peer_addr_len );
        return;

3046 3047 3048 3049 3050 3051 3052 3053
    case IOCTL_AFD_WINE_DEFER:
    {
        const obj_handle_t *handle = get_req_data();
        struct sock *acceptsock;

        if (get_req_data_size() < sizeof(*handle))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3054
            return;
3055 3056 3057
        }

        acceptsock = (struct sock *)get_handle_obj( current->process, *handle, 0, &sock_ops );
3058
        if (!acceptsock) return;
3059 3060

        sock->deferred = acceptsock;
3061
        return;
3062 3063
    }

3064 3065 3066 3067 3068 3069 3070
    case IOCTL_AFD_WINE_GET_INFO:
    {
        struct afd_get_info_params params;

        if (get_reply_max_size() < sizeof(params))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3071
            return;
3072 3073 3074 3075 3076 3077
        }

        params.family = sock->family;
        params.type = sock->type;
        params.protocol = sock->proto;
        set_reply_data( &params, sizeof(params) );
3078
        return;
3079 3080
    }

3081 3082 3083 3084 3085 3086 3087
    case IOCTL_AFD_WINE_GET_SO_ACCEPTCONN:
    {
        int listening = (sock->state == SOCK_LISTENING);

        if (get_reply_max_size() < sizeof(listening))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3088
            return;
3089 3090 3091
        }

        set_reply_data( &listening, sizeof(listening) );
3092
        return;
3093 3094
    }

3095 3096 3097 3098 3099 3100 3101 3102
    case IOCTL_AFD_WINE_GET_SO_ERROR:
    {
        int error;
        unsigned int i;

        if (get_reply_max_size() < sizeof(error))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3103
            return;
3104 3105
        }

3106
        error = sock_error( sock );
3107 3108 3109 3110 3111 3112
        if (!error)
        {
            for (i = 0; i < ARRAY_SIZE( sock->errors ); ++i)
            {
                if (sock->errors[i])
                {
3113
                    error = sock->errors[i];
3114 3115 3116 3117 3118
                    break;
                }
            }
        }

3119
        error = sock_get_error( error );
3120
        set_reply_data( &error, sizeof(error) );
3121
        return;
3122 3123
    }

3124 3125 3126 3127 3128 3129 3130
    case IOCTL_AFD_WINE_GET_SO_RCVBUF:
    {
        int rcvbuf = sock->rcvbuf;

        if (get_reply_max_size() < sizeof(rcvbuf))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3131
            return;
3132 3133 3134
        }

        set_reply_data( &rcvbuf, sizeof(rcvbuf) );
3135
        return;
3136 3137
    }

3138 3139
    case IOCTL_AFD_WINE_SET_SO_RCVBUF:
    {
3140
        DWORD rcvbuf, set_rcvbuf;
3141 3142 3143 3144

        if (get_req_data_size() < sizeof(rcvbuf))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3145
            return;
3146 3147
        }
        rcvbuf = *(DWORD *)get_req_data();
3148
        set_rcvbuf = max( rcvbuf, MIN_RCVBUF );
3149

3150
        if (!setsockopt( unix_fd, SOL_SOCKET, SO_RCVBUF, (char *)&set_rcvbuf, sizeof(set_rcvbuf) ))
3151 3152
            sock->rcvbuf = rcvbuf;
        else
3153
            set_error( sock_get_ntstatus( errno ) );
3154
        return;
3155 3156
    }

3157 3158 3159 3160 3161 3162 3163
    case IOCTL_AFD_WINE_GET_SO_RCVTIMEO:
    {
        DWORD rcvtimeo = sock->rcvtimeo;

        if (get_reply_max_size() < sizeof(rcvtimeo))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3164
            return;
3165 3166 3167
        }

        set_reply_data( &rcvtimeo, sizeof(rcvtimeo) );
3168
        return;
3169 3170 3171 3172 3173 3174 3175 3176 3177
    }

    case IOCTL_AFD_WINE_SET_SO_RCVTIMEO:
    {
        DWORD rcvtimeo;

        if (get_req_data_size() < sizeof(rcvtimeo))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3178
            return;
3179 3180 3181 3182
        }
        rcvtimeo = *(DWORD *)get_req_data();

        sock->rcvtimeo = rcvtimeo;
3183
        return;
3184 3185
    }

3186
    /* BSD socket SO_REUSEADDR is not compatible with winsock semantics. */
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197
    case IOCTL_AFD_WINE_SET_SO_REUSEADDR:
    {
        int reuse, ret;

        if (get_req_data_size() < sizeof(reuse))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
            return;
        }

        reuse = *(int *)get_req_data();
3198 3199 3200 3201 3202 3203 3204

        if (reuse && sock->exclusiveaddruse)
        {
            set_error( STATUS_INVALID_PARAMETER );
            return;
        }

3205 3206 3207 3208
        if (is_tcp_socket( sock ))
            ret = 0;
        else
            ret = setsockopt( unix_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse) );
3209 3210 3211 3212 3213
#ifdef __APPLE__
        if (!ret) ret = setsockopt( unix_fd, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse) );
#endif
        if (ret)
            set_error( sock_get_ntstatus( errno ) );
3214 3215
        else
            sock->reuseaddr = !!reuse;
3216 3217 3218
        return;
    }

3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229
    case IOCTL_AFD_WINE_SET_SO_EXCLUSIVEADDRUSE:
    {
        int exclusive;

        if (get_req_data_size() < sizeof(exclusive))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
            return;
        }

        exclusive = *(int *)get_req_data();
3230 3231 3232 3233 3234
        if (exclusive && sock->reuseaddr)
        {
            set_error( STATUS_INVALID_PARAMETER );
            return;
        }
3235 3236 3237 3238
        sock->exclusiveaddruse = !!exclusive;
        return;
    }

3239 3240 3241 3242 3243 3244 3245
    case IOCTL_AFD_WINE_GET_SO_SNDBUF:
    {
        int sndbuf = sock->sndbuf;

        if (get_reply_max_size() < sizeof(sndbuf))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3246
            return;
3247 3248 3249
        }

        set_reply_data( &sndbuf, sizeof(sndbuf) );
3250
        return;
3251 3252
    }

3253 3254 3255 3256 3257 3258 3259
    case IOCTL_AFD_WINE_SET_SO_SNDBUF:
    {
        DWORD sndbuf;

        if (get_req_data_size() < sizeof(sndbuf))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3260
            return;
3261 3262 3263 3264 3265 3266 3267
        }
        sndbuf = *(DWORD *)get_req_data();

#ifdef __APPLE__
        if (!sndbuf)
        {
            /* setsockopt fails if a zero value is passed */
3268
            sock->sndbuf = sndbuf;
3269
            return;
3270 3271 3272
        }
#endif

3273 3274 3275
        if (!setsockopt( unix_fd, SOL_SOCKET, SO_SNDBUF, (char *)&sndbuf, sizeof(sndbuf) ))
            sock->sndbuf = sndbuf;
        else
3276
            set_error( sock_get_ntstatus( errno ) );
3277
        return;
3278 3279
    }

3280 3281 3282 3283 3284 3285 3286
    case IOCTL_AFD_WINE_GET_SO_SNDTIMEO:
    {
        DWORD sndtimeo = sock->sndtimeo;

        if (get_reply_max_size() < sizeof(sndtimeo))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3287
            return;
3288 3289 3290
        }

        set_reply_data( &sndtimeo, sizeof(sndtimeo) );
3291
        return;
3292 3293 3294 3295 3296 3297 3298 3299 3300
    }

    case IOCTL_AFD_WINE_SET_SO_SNDTIMEO:
    {
        DWORD sndtimeo;

        if (get_req_data_size() < sizeof(sndtimeo))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3301
            return;
3302 3303 3304 3305
        }
        sndtimeo = *(DWORD *)get_req_data();

        sock->sndtimeo = sndtimeo;
3306
        return;
3307 3308
    }

3309 3310 3311 3312 3313 3314 3315
    case IOCTL_AFD_WINE_GET_SO_CONNECT_TIME:
    {
        DWORD time = ~0u;

        if (get_reply_max_size() < sizeof(time))
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
3316
            return;
3317 3318 3319 3320 3321 3322
        }

        if (sock->state == SOCK_CONNECTED)
            time = (current_time - sock->connect_time) / 10000000;

        set_reply_data( &time, sizeof(time) );
3323
        return;
3324 3325
    }

3326 3327 3328 3329 3330 3331 3332 3333 3334 3335
    case IOCTL_AFD_WINE_GET_SO_REUSEADDR:
    {
        int reuse;

        if (!get_reply_max_size())
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
            return;
        }

3336 3337
        reuse = sock->reuseaddr;
        set_reply_data( &reuse, min( sizeof(reuse), get_reply_max_size() ));
3338 3339 3340
        return;
    }

3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355
    case IOCTL_AFD_WINE_GET_SO_EXCLUSIVEADDRUSE:
    {
        int exclusive;

        if (!get_reply_max_size())
        {
            set_error( STATUS_BUFFER_TOO_SMALL );
            return;
        }

        exclusive = sock->exclusiveaddruse;
        set_reply_data( &exclusive, min( sizeof(exclusive), get_reply_max_size() ));
        return;
    }

3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404
    case IOCTL_AFD_POLL:
    {
        if (get_reply_max_size() < get_req_data_size())
        {
            set_error( STATUS_INVALID_PARAMETER );
            return;
        }

        if (is_machine_64bit( current->process->machine ))
        {
            const struct afd_poll_params_64 *params = get_req_data();

            if (get_req_data_size() < sizeof(struct afd_poll_params_64) ||
                get_req_data_size() < offsetof( struct afd_poll_params_64, sockets[params->count] ))
            {
                set_error( STATUS_INVALID_PARAMETER );
                return;
            }

            poll_socket( sock, async, params->exclusive, params->timeout, params->count, params->sockets );
        }
        else
        {
            const struct afd_poll_params_32 *params = get_req_data();
            struct afd_poll_socket_64 *sockets;
            unsigned int i;

            if (get_req_data_size() < sizeof(struct afd_poll_params_32) ||
                get_req_data_size() < offsetof( struct afd_poll_params_32, sockets[params->count] ))
            {
                set_error( STATUS_INVALID_PARAMETER );
                return;
            }

            if (!(sockets = mem_alloc( params->count * sizeof(*sockets) ))) return;
            for (i = 0; i < params->count; ++i)
            {
                sockets[i].socket = params->sockets[i].socket;
                sockets[i].flags = params->sockets[i].flags;
                sockets[i].status = params->sockets[i].status;
            }

            poll_socket( sock, async, params->exclusive, params->timeout, params->count, sockets );
            free( sockets );
        }

        return;
    }

3405 3406
    default:
        set_error( STATUS_NOT_SUPPORTED );
3407
        return;
3408 3409 3410
    }
}

3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431
static void handle_exclusive_poll(struct poll_req *req)
{
    unsigned int i;

    for (i = 0; i < req->count; ++i)
    {
        struct sock *sock = req->sockets[i].sock;
        struct poll_req *main_poll = sock->main_poll;

        if (main_poll && main_poll->exclusive && req->exclusive)
        {
            complete_async_poll( main_poll, STATUS_SUCCESS );
            main_poll = NULL;
        }

        if (!main_poll)
            sock->main_poll = req;
    }
}

static void poll_socket( struct sock *poll_sock, struct async *async, int exclusive, timeout_t timeout,
3432
                         unsigned int count, const struct afd_poll_socket_64 *sockets )
3433
{
3434
    BOOL signaled = FALSE;
3435 3436 3437
    struct poll_req *req;
    unsigned int i, j;

3438 3439 3440
    if (!count)
    {
        set_error( STATUS_INVALID_PARAMETER );
3441
        return;
3442
    }
3443 3444

    if (!(req = mem_alloc( offsetof( struct poll_req, sockets[count] ) )))
3445
        return;
3446 3447

    req->timeout = NULL;
3448
    req->pending = 0;
3449 3450 3451 3452
    if (timeout && timeout != TIMEOUT_INFINITE &&
        !(req->timeout = add_timeout_user( timeout, async_poll_timeout, req )))
    {
        free( req );
3453
        return;
3454
    }
3455
    req->orig_timeout = timeout;
3456 3457 3458

    for (i = 0; i < count; ++i)
    {
3459
        req->sockets[i].sock = (struct sock *)get_handle_obj( current->process, sockets[i].socket, 0, &sock_ops );
3460 3461
        if (!req->sockets[i].sock)
        {
3462
            for (j = 0; j < i; ++j) release_object( req->sockets[j].sock );
3463 3464
            if (req->timeout) remove_timeout_user( req->timeout );
            free( req );
3465
            return;
3466
        }
3467 3468 3469
        req->sockets[i].handle = sockets[i].socket;
        req->sockets[i].mask = sockets[i].flags;
        req->sockets[i].flags = 0;
3470 3471
    }

3472
    req->exclusive = exclusive;
3473 3474 3475 3476
    req->count = count;
    req->async = (struct async *)grab_object( async );
    req->iosb = async_get_iosb( async );

3477 3478
    handle_exclusive_poll(req);

3479 3480 3481 3482 3483 3484 3485
    list_add_tail( &poll_list, &req->entry );
    async_set_completion_callback( async, free_poll_req, req );
    queue_async( &poll_sock->poll_q, async );

    for (i = 0; i < count; ++i)
    {
        struct sock *sock = req->sockets[i].sock;
3486
        int mask = req->sockets[i].mask;
3487
        struct pollfd pollfd;
3488

3489 3490 3491 3492
        pollfd.fd = get_unix_fd( sock->fd );
        pollfd.events = poll_flags_from_afd( sock, mask );
        if (pollfd.events >= 0 && poll( &pollfd, 1, 0 ) >= 0)
            sock_poll_event( sock->fd, pollfd.revents );
3493 3494 3495 3496

        /* FIXME: do other error conditions deserve a similar treatment? */
        if (sock->state != SOCK_CONNECTING && sock->errors[AFD_POLL_BIT_CONNECT_ERR] && (mask & AFD_POLL_CONNECT_ERR))
        {
3497 3498
            req->sockets[i].flags |= AFD_POLL_CONNECT_ERR;
            req->sockets[i].status = sock_get_ntstatus( sock->errors[AFD_POLL_BIT_CONNECT_ERR] );
3499
        }
3500 3501 3502

        if (req->sockets[i].flags)
            signaled = TRUE;
3503 3504
    }

3505
    if (!timeout || signaled)
3506
        complete_async_poll( req, STATUS_SUCCESS );
3507 3508
    else
        req->pending = 1;
3509 3510 3511 3512 3513 3514

    for (i = 0; i < req->count; ++i)
        sock_reselect( req->sockets[i].sock );
    set_error( STATUS_PENDING );
}

3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536
#ifdef HAVE_LINUX_RTNETLINK_H

/* only keep one ifchange object around, all sockets waiting for wakeups will look to it */
static struct object *ifchange_object;

static void ifchange_dump( struct object *obj, int verbose );
static struct fd *ifchange_get_fd( struct object *obj );
static void ifchange_destroy( struct object *obj );

static int ifchange_get_poll_events( struct fd *fd );
static void ifchange_poll_event( struct fd *fd, int event );

struct ifchange
{
    struct object       obj;     /* object header */
    struct fd          *fd;      /* interface change file descriptor */
    struct list         sockets; /* list of sockets to send interface change notifications */
};

static const struct object_ops ifchange_ops =
{
    sizeof(struct ifchange), /* size */
3537
    &no_type,                /* type */
3538
    ifchange_dump,           /* dump */
3539
    no_add_queue,            /* add_queue */
3540 3541 3542 3543 3544
    NULL,                    /* remove_queue */
    NULL,                    /* signaled */
    no_satisfied,            /* satisfied */
    no_signal,               /* signal */
    ifchange_get_fd,         /* get_fd */
3545
    default_map_access,      /* map_access */
3546 3547
    default_get_sd,          /* get_sd */
    default_set_sd,          /* set_sd */
3548
    no_get_full_name,        /* get_full_name */
3549
    no_lookup_name,          /* lookup_name */
3550 3551
    no_link_name,            /* link_name */
    NULL,                    /* unlink_name */
3552
    no_open_file,            /* open_file */
3553
    no_kernel_obj_list,      /* get_kernel_obj_list */
3554 3555 3556 3557 3558 3559 3560 3561 3562
    no_close_handle,         /* close_handle */
    ifchange_destroy         /* destroy */
};

static const struct fd_ops ifchange_fd_ops =
{
    ifchange_get_poll_events, /* get_poll_events */
    ifchange_poll_event,      /* poll_event */
    NULL,                     /* get_fd_type */
3563 3564 3565
    no_fd_read,               /* read */
    no_fd_write,              /* write */
    no_fd_flush,              /* flush */
3566
    no_fd_get_file_info,      /* get_file_info */
3567
    no_fd_get_volume_info,    /* get_volume_info */
3568
    no_fd_ioctl,              /* ioctl */
3569
    NULL,                     /* cancel_async */
3570
    NULL,                     /* queue_async */
3571
    NULL                      /* reselect_async */
3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
};

static void ifchange_dump( struct object *obj, int verbose )
{
    assert( obj->ops == &ifchange_ops );
    fprintf( stderr, "Interface change\n" );
}

static struct fd *ifchange_get_fd( struct object *obj )
{
    struct ifchange *ifchange = (struct ifchange *)obj;
    return (struct fd *)grab_object( ifchange->fd );
}

static void ifchange_destroy( struct object *obj )
{
    struct ifchange *ifchange = (struct ifchange *)obj;
    assert( obj->ops == &ifchange_ops );

    release_object( ifchange->fd );

    /* reset the global ifchange object so that it will be recreated if it is needed again */
    assert( obj == ifchange_object );
    ifchange_object = NULL;
}

static int ifchange_get_poll_events( struct fd *fd )
3599
{
3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614
    return POLLIN;
}

/* wake up all the sockets waiting for a change notification event */
static void ifchange_wake_up( struct object *obj, unsigned int status )
{
    struct ifchange *ifchange = (struct ifchange *)obj;
    struct list *ptr, *next;
    assert( obj->ops == &ifchange_ops );
    assert( obj == ifchange_object );

    LIST_FOR_EACH_SAFE( ptr, next, &ifchange->sockets )
    {
        struct sock *sock = LIST_ENTRY( ptr, struct sock, ifchange_entry );

3615
        assert( sock->ifchange_obj );
3616
        async_wake_up( &sock->ifchange_q, status ); /* issue ifchange notification for the socket */
3617
        sock_release_ifchange( sock ); /* remove socket from list and decrement ifchange refcount */
3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630
    }
}

static void ifchange_poll_event( struct fd *fd, int event )
{
    struct object *ifchange = get_fd_user( fd );
    unsigned int status = STATUS_PENDING;
    char buffer[PIPE_BUF];
    int r;

    r = recv( get_unix_fd(fd), buffer, sizeof(buffer), MSG_DONTWAIT );
    if (r < 0)
    {
3631 3632
        if (errno == EWOULDBLOCK || (EWOULDBLOCK != EAGAIN && errno == EAGAIN))
            return;  /* retry when poll() says the socket is ready */
3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672
        status = sock_get_ntstatus( errno );
    }
    else if (r > 0)
    {
        struct nlmsghdr *nlh;

        for (nlh = (struct nlmsghdr *)buffer; NLMSG_OK(nlh, r); nlh = NLMSG_NEXT(nlh, r))
        {
            if (nlh->nlmsg_type == NLMSG_DONE)
                break;
            if (nlh->nlmsg_type == RTM_NEWADDR || nlh->nlmsg_type == RTM_DELADDR)
                status = STATUS_SUCCESS;
        }
    }
    else status = STATUS_CANCELLED;

    if (status != STATUS_PENDING) ifchange_wake_up( ifchange, status );
}

#endif

/* we only need one of these interface notification objects, all of the sockets dependent upon
 * it will wake up when a notification event occurs */
 static struct object *get_ifchange( void )
 {
#ifdef HAVE_LINUX_RTNETLINK_H
    struct ifchange *ifchange;
    struct sockaddr_nl addr;
    int unix_fd;

    if (ifchange_object)
    {
        /* increment the refcount for each socket that uses the ifchange object */
        return grab_object( ifchange_object );
    }

    /* create the socket we need for processing interface change notifications */
    unix_fd = socket( PF_NETLINK, SOCK_RAW, NETLINK_ROUTE );
    if (unix_fd == -1)
    {
3673
        set_error( sock_get_ntstatus( errno ));
3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
        return NULL;
    }
    fcntl( unix_fd, F_SETFL, O_NONBLOCK ); /* make socket nonblocking */
    memset( &addr, 0, sizeof(addr) );
    addr.nl_family = AF_NETLINK;
    addr.nl_groups = RTMGRP_IPV4_IFADDR;
    /* bind the socket to the special netlink kernel interface */
    if (bind( unix_fd, (struct sockaddr *)&addr, sizeof(addr) ) == -1)
    {
        close( unix_fd );
3684
        set_error( sock_get_ntstatus( errno ));
3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705
        return NULL;
    }
    if (!(ifchange = alloc_object( &ifchange_ops )))
    {
        close( unix_fd );
        set_error( STATUS_NO_MEMORY );
        return NULL;
    }
    list_init( &ifchange->sockets );
    if (!(ifchange->fd = create_anonymous_fd( &ifchange_fd_ops, unix_fd, &ifchange->obj, 0 )))
    {
        release_object( ifchange );
        set_error( STATUS_NO_MEMORY );
        return NULL;
    }
    set_fd_events( ifchange->fd, POLLIN ); /* enable read wakeup on the file descriptor */

    /* the ifchange object is now successfully configured */
    ifchange_object = &ifchange->obj;
    return &ifchange->obj;
#else
3706 3707
    set_error( STATUS_NOT_SUPPORTED );
    return NULL;
3708
#endif
3709 3710
}

3711
/* add the socket to the interface change notification list */
3712 3713
static void ifchange_add_sock( struct object *obj, struct sock *sock )
{
3714 3715 3716 3717 3718
#ifdef HAVE_LINUX_RTNETLINK_H
    struct ifchange *ifchange = (struct ifchange *)obj;

    list_add_tail( &ifchange->sockets, &sock->ifchange_entry );
#endif
3719 3720 3721
}

/* create a new ifchange queue for a specific socket or, if one already exists, reuse the existing one */
3722
static struct object *sock_get_ifchange( struct sock *sock )
3723 3724 3725
{
    struct object *ifchange;

3726 3727
    if (sock->ifchange_obj) /* reuse existing ifchange_obj for this socket */
        return sock->ifchange_obj;
3728 3729 3730 3731 3732 3733 3734

    if (!(ifchange = get_ifchange()))
        return NULL;

    /* add the socket to the ifchange notification list */
    ifchange_add_sock( ifchange, sock );
    sock->ifchange_obj = ifchange;
3735
    return ifchange;
3736 3737 3738
}

/* destroy an existing ifchange queue for a specific socket */
3739
static void sock_release_ifchange( struct sock *sock )
3740
{
3741
    if (sock->ifchange_obj)
3742 3743 3744
    {
        list_remove( &sock->ifchange_entry );
        release_object( sock->ifchange_obj );
3745
        sock->ifchange_obj = NULL;
3746 3747 3748
    }
}

3749
static void socket_device_dump( struct object *obj, int verbose );
3750 3751
static struct object *socket_device_lookup_name( struct object *obj, struct unicode_str *name,
                                                 unsigned int attr, struct object *root );
3752 3753 3754 3755 3756 3757
static struct object *socket_device_open_file( struct object *obj, unsigned int access,
                                               unsigned int sharing, unsigned int options );

static const struct object_ops socket_device_ops =
{
    sizeof(struct object),      /* size */
3758
    &device_type,               /* type */
3759 3760 3761 3762 3763 3764 3765
    socket_device_dump,         /* dump */
    no_add_queue,               /* add_queue */
    NULL,                       /* remove_queue */
    NULL,                       /* signaled */
    no_satisfied,               /* satisfied */
    no_signal,                  /* signal */
    no_get_fd,                  /* get_fd */
3766
    default_map_access,         /* map_access */
3767 3768
    default_get_sd,             /* get_sd */
    default_set_sd,             /* set_sd */
3769
    default_get_full_name,      /* get_full_name */
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783
    socket_device_lookup_name,  /* lookup_name */
    directory_link_name,        /* link_name */
    default_unlink_name,        /* unlink_name */
    socket_device_open_file,    /* open_file */
    no_kernel_obj_list,         /* get_kernel_obj_list */
    no_close_handle,            /* close_handle */
    no_destroy                  /* destroy */
};

static void socket_device_dump( struct object *obj, int verbose )
{
    fputs( "Socket device\n", stderr );
}

3784 3785
static struct object *socket_device_lookup_name( struct object *obj, struct unicode_str *name,
                                                 unsigned int attr, struct object *root )
3786
{
3787
    if (name) name->len = 0;
3788 3789 3790 3791 3792 3793
    return NULL;
}

static struct object *socket_device_open_file( struct object *obj, unsigned int access,
                                               unsigned int sharing, unsigned int options )
{
3794 3795 3796 3797 3798 3799 3800 3801 3802
    struct sock *sock;

    if (!(sock = create_socket())) return NULL;
    if (!(sock->fd = alloc_pseudo_fd( &sock_fd_ops, &sock->obj, options )))
    {
        release_object( sock );
        return NULL;
    }
    return &sock->obj;
3803 3804
}

3805 3806
struct object *create_socket_device( struct object *root, const struct unicode_str *name,
                                     unsigned int attr, const struct security_descriptor *sd )
3807
{
3808
    return create_named_object( root, &socket_device_ops, name, attr, sd );
3809 3810
}

3811 3812 3813
DECL_HANDLER(recv_socket)
{
    struct sock *sock = (struct sock *)get_handle_obj( current->process, req->async.handle, 0, &sock_ops );
3814
    unsigned int status = STATUS_PENDING;
3815 3816 3817 3818 3819 3820 3821
    timeout_t timeout = 0;
    struct async *async;
    struct fd *fd;

    if (!sock) return;
    fd = sock->fd;

3822 3823
    if (!req->force_async && !sock->nonblocking && is_fd_overlapped( fd ))
        timeout = (timeout_t)sock->rcvtimeo * -10000;
3824

3825 3826
    if (sock->rd_shutdown) status = STATUS_PIPE_DISCONNECTED;
    else if (!async_queued( &sock->read_q ))
3827
    {
3828 3829 3830 3831
        /* If read_q is not empty, we cannot really tell if the already queued
         * asyncs will not consume all available data; if there's no data
         * available, the current request won't be immediately satiable.
         */
3832 3833
        if ((!req->force_async && sock->nonblocking) ||
            check_fd_events( sock->fd, req->oob && !is_oobinline( sock ) ? POLLPRI : POLLIN ))
3834 3835 3836
        {
            /* Give the client opportunity to complete synchronously.
             * If it turns out that the I/O request is not actually immediately satiable,
3837 3838 3839 3840 3841 3842 3843 3844
             * the client may then choose to re-queue the async (with STATUS_PENDING).
             *
             * Note: If the nonblocking flag is set, we don't poll the socket
             * here and always opt for synchronous completion first.  This is
             * because the application has probably seen POLLIN already from a
             * preceding select()/poll() call before it requested to receive
             * data.
             */
3845 3846 3847 3848
            status = STATUS_ALERTED;
        }
    }

3849 3850 3851
    if (status == STATUS_PENDING && !req->force_async && sock->nonblocking)
        status = STATUS_DEVICE_NOT_READY;

3852 3853
    sock->pending_events &= ~(req->oob ? AFD_POLL_OOB : AFD_POLL_READ);
    sock->reported_events &= ~(req->oob ? AFD_POLL_OOB : AFD_POLL_READ);
3854 3855 3856 3857 3858 3859 3860 3861

    if ((async = create_request_async( fd, get_fd_comp_flags( fd ), &req->async )))
    {
        set_error( status );

        if (timeout)
            async_set_timeout( async, timeout, STATUS_IO_TIMEOUT );

3862
        if (status == STATUS_PENDING || status == STATUS_ALERTED)
3863 3864 3865 3866 3867
            queue_async( &sock->read_q, async );

        /* always reselect; we changed reported_events above */
        sock_reselect( sock );

3868
        reply->wait = async_handoff( async, NULL, 0 );
3869
        reply->options = get_fd_options( fd );
3870
        reply->nonblocking = sock->nonblocking;
3871 3872 3873 3874
        release_object( async );
    }
    release_object( sock );
}
3875

3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894
static void send_socket_completion_callback( void *private )
{
    struct send_req *send_req = private;
    struct iosb *iosb = send_req->iosb;
    struct sock *sock = send_req->sock;

    if (iosb->status != STATUS_SUCCESS)
    {
        /* send() calls only clear and reselect events if unsuccessful. */
        sock->pending_events &= ~AFD_POLL_WRITE;
        sock->reported_events &= ~AFD_POLL_WRITE;
        sock_reselect( sock );
    }

    release_object( iosb );
    release_object( sock );
    free( send_req );
}

3895 3896 3897
DECL_HANDLER(send_socket)
{
    struct sock *sock = (struct sock *)get_handle_obj( current->process, req->async.handle, 0, &sock_ops );
3898
    unsigned int status = STATUS_PENDING;
3899 3900 3901
    timeout_t timeout = 0;
    struct async *async;
    struct fd *fd;
3902
    int bind_errno = 0;
3903 3904 3905 3906

    if (!sock) return;
    fd = sock->fd;

3907
    if (sock->type == WS_SOCK_DGRAM && !sock->bound)
3908 3909
    {
        union unix_sockaddr unix_addr;
3910 3911 3912 3913 3914 3915
        socklen_t unix_len;
        int unix_fd = get_unix_fd( fd );

        unix_len = get_unix_sockaddr_any( &unix_addr, sock->family );
        if (bind( unix_fd, &unix_addr.addr, unix_len ) < 0)
            bind_errno = errno;
3916

3917 3918
        if (getsockname( unix_fd, &unix_addr.addr, &unix_len ) >= 0)
        {
3919
            sock->addr_len = sockaddr_from_unix( &unix_addr, &sock->addr.addr, sizeof(sock->addr) );
3920 3921
            sock->bound = 1;
        }
3922
        else if (!bind_errno) bind_errno = errno;
3923 3924
    }

3925 3926
    if (!req->force_async && !sock->nonblocking && is_fd_overlapped( fd ))
        timeout = (timeout_t)sock->sndtimeo * -10000;
3927

3928 3929 3930
    if (bind_errno) status = sock_get_ntstatus( bind_errno );
    else if (sock->wr_shutdown) status = STATUS_PIPE_DISCONNECTED;
    else if (!async_queued( &sock->write_q ))
3931 3932 3933 3934 3935
    {
        /* If write_q is not empty, we cannot really tell if the already queued
         * asyncs will not consume all available space; if there's no space
         * available, the current request won't be immediately satiable.
         */
3936
        if ((!req->force_async && sock->nonblocking) || check_fd_events( sock->fd, POLLOUT ))
3937 3938 3939
        {
            /* Give the client opportunity to complete synchronously.
             * If it turns out that the I/O request is not actually immediately satiable,
3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956
             * the client may then choose to re-queue the async (with STATUS_PENDING).
             *
             * Note: If the nonblocking flag is set, we don't poll the socket
             * here and always opt for synchronous completion first.  This is
             * because the application has probably seen POLLOUT already from a
             * preceding select()/poll() call before it requested to send data.
             *
             * Furthermore, some applications expect that any send() call on a
             * socket that has indicated POLLOUT beforehand never fails with
             * WSAEWOULDBLOCK.  It's possible that Linux poll() may yield
             * POLLOUT on the first call but not the second, even if no send()
             * call has been made in the meanwhile.  This can happen for a
             * number of reasons; for example, TCP fragmentation may consume
             * extra buffer space for each packet that has been split out, or
             * the TCP/IP networking stack may decide to shrink the send buffer
             * due to memory pressure.
             */
3957 3958 3959 3960
            status = STATUS_ALERTED;
        }
    }

3961 3962 3963
    if (status == STATUS_PENDING && !req->force_async && sock->nonblocking)
        status = STATUS_DEVICE_NOT_READY;

3964 3965
    if ((async = create_request_async( fd, get_fd_comp_flags( fd ), &req->async )))
    {
3966 3967 3968 3969
        struct send_req *send_req;
        struct iosb *iosb = async_get_iosb( async );

        if ((send_req = mem_alloc( sizeof(*send_req) )))
3970
        {
3971 3972 3973
            send_req->iosb = (struct iosb *)grab_object( iosb );
            send_req->sock = (struct sock *)grab_object( sock );
            async_set_completion_callback( async, send_socket_completion_callback, send_req );
3974
        }
3975 3976 3977 3978 3979
        else if (status == STATUS_PENDING || status == STATUS_DEVICE_NOT_READY)
            status = STATUS_NO_MEMORY;

        release_object( iosb );

3980 3981 3982 3983 3984
        set_error( status );

        if (timeout)
            async_set_timeout( async, timeout, STATUS_IO_TIMEOUT );

3985
        if (status == STATUS_PENDING || status == STATUS_ALERTED)
3986
        {
3987
            queue_async( &sock->write_q, async );
3988 3989
            sock_reselect( sock );
        }
3990

3991
        reply->wait = async_handoff( async, NULL, 0 );
3992
        reply->options = get_fd_options( fd );
3993
        reply->nonblocking = sock->nonblocking;
3994 3995 3996 3997
        release_object( async );
    }
    release_object( sock );
}
3998

3999 4000 4001 4002
DECL_HANDLER(socket_get_events)
{
    struct sock *sock = (struct sock *)get_handle_obj( current->process, req->handle, 0, &sock_ops );
    unsigned int status[13];
4003
    struct event *event = NULL;
4004 4005 4006 4007 4008 4009 4010 4011 4012 4013
    unsigned int i;

    if (get_reply_max_size() < sizeof(status))
    {
        set_error( STATUS_INVALID_PARAMETER );
        return;
    }

    if (!sock) return;

4014 4015 4016 4017 4018 4019 4020 4021 4022
    if (req->event)
    {
        if (!(event = get_event_obj( current->process, req->event, EVENT_MODIFY_STATE )))
        {
            release_object( sock );
            return;
        }
    }

4023 4024 4025 4026 4027 4028 4029
    reply->flags = sock->pending_events & sock->mask;
    for (i = 0; i < ARRAY_SIZE( status ); ++i)
        status[i] = sock_get_ntstatus( sock->errors[i] );

    sock->pending_events &= ~sock->mask;
    sock_reselect( sock );

4030 4031 4032 4033 4034 4035
    if (event)
    {
        reset_event( event );
        release_object( event );
    }

4036 4037 4038 4039 4040
    set_reply_data( status, sizeof(status) );

    release_object( sock );
}

4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083
DECL_HANDLER(socket_send_icmp_id)
{
    struct sock *sock = (struct sock *)get_handle_obj( current->process, req->handle, 0, &sock_ops );

    if (!sock) return;

    if (sock->icmp_fixup_data_len == MAX_ICMP_HISTORY_LENGTH)
    {
        memmove( sock->icmp_fixup_data, sock->icmp_fixup_data + 1,
                 sizeof(*sock->icmp_fixup_data) * (MAX_ICMP_HISTORY_LENGTH - 1) );
        --sock->icmp_fixup_data_len;
    }

    sock->icmp_fixup_data[sock->icmp_fixup_data_len].icmp_id = req->icmp_id;
    sock->icmp_fixup_data[sock->icmp_fixup_data_len].icmp_seq = req->icmp_seq;
    ++sock->icmp_fixup_data_len;

    release_object( sock );
}

DECL_HANDLER(socket_get_icmp_id)
{
    struct sock *sock = (struct sock *)get_handle_obj( current->process, req->handle, 0, &sock_ops );
    unsigned int i;

    if (!sock) return;

    for (i = 0; i < sock->icmp_fixup_data_len; ++i)
    {
        if (sock->icmp_fixup_data[i].icmp_seq == req->icmp_seq)
        {
            reply->icmp_id = sock->icmp_fixup_data[i].icmp_id;
            --sock->icmp_fixup_data_len;
            memmove( &sock->icmp_fixup_data[i], &sock->icmp_fixup_data[i + 1],
                     (sock->icmp_fixup_data_len - i) * sizeof(*sock->icmp_fixup_data) );
            release_object( sock );
            return;
        }
    }

    set_error( STATUS_NOT_FOUND );
    release_object( sock );
}