aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


client/runtime/linux_network.c (28044B)


      1 #define _GNU_SOURCE
      2 #include "linux_network.h"
      3 #include "linux_sync.h"
      4 #include <arpa/inet.h>
      5 #include <errno.h>
      6 #include <fcntl.h>
      7 #include <pthread.h>
      8 #include <poll.h>
      9 #include <sys/ioctl.h>
     10 #include <sys/epoll.h>
     11 #include <time.h>
     12 #include <unistd.h>
     13 
     14 static unsigned startup_count;
     15 static pthread_mutex_t socket_mutex = PTHREAD_MUTEX_INITIALIZER;
     16 struct guest_socket {
     17     uint32_t handle;
     18     int descriptor, connecting;
     19     unsigned shutdown; /* Local read/write bits 1/2; observed peer TCP FIN bit 4. */
     20     struct semaphore_handle *event;
     21     uint32_t selected, armed, recorded, close_error, receive_error;
     22     int watched;
     23     struct guest_socket *next;
     24 };
     25 static struct guest_socket *sockets;
     26 static uint32_t next_handle = 0x09000000u;
     27 static int socket_events = -1;
     28 
     29 static uint32_t socket_error(int error)
     30 {
     31     switch (error) {
     32     case EBADF: case ENOTSOCK: return 10038;
     33     case EINTR: return 10004;
     34     case EACCES: case EPERM: return 10013;
     35     case EFAULT: return 10014;
     36     case EINVAL: return 10022;
     37     case EMFILE: case ENFILE: return 10024;
     38     case EAGAIN: return 10035;
     39     case EINPROGRESS: return 10035;
     40     case EALREADY: return 10037;
     41     case EPROTONOSUPPORT: return 10043;
     42     case ESOCKTNOSUPPORT: return 10044;
     43     case EOPNOTSUPP: return 10045;
     44     case EAFNOSUPPORT: return 10047;
     45     case EADDRINUSE: return 10048;
     46     case EADDRNOTAVAIL: return 10049;
     47     case ENETDOWN: return 10050;
     48     case ENETUNREACH: return 10051;
     49     case ECONNABORTED: return 10053;
     50     case ECONNRESET: return 10054;
     51     case ENOBUFS: case ENOMEM: return 10055;
     52     case EISCONN: return 10056;
     53     case ENOTCONN: return 10057;
     54     case EPIPE: return 10058;
     55     case ETIMEDOUT: return 10060;
     56     case ECONNREFUSED: return 10061;
     57     case EHOSTUNREACH: return 10065;
     58     default:
     59         fprintf(stderr, "Unmapped socket error: %s\n", strerror(error));
     60         abort();
     61     }
     62 }
     63 
     64 static struct guest_socket *find_socket_locked(uint32_t handle)
     65 {
     66     if (!startup_count) { MEM32(g_fs_base + 0x34) = 10093; return NULL; }
     67     for (struct guest_socket *socket = sockets; socket; socket = socket->next)
     68         if (socket->handle == handle) return socket;
     69     MEM32(g_fs_base + 0x34) = 10038;
     70     return NULL;
     71 }
     72 
     73 static void arm_socket_events_locked(struct guest_socket *socket)
     74 {
     75     uint32_t mask = socket->selected & socket->armed;
     76     if (!mask) {
     77         if (socket->watched && epoll_ctl(socket_events, EPOLL_CTL_DEL, socket->descriptor, NULL)) abort();
     78         socket->watched = 0;
     79         return;
     80     }
     81     struct epoll_event event = {.events = EPOLLONESHOT, .data.u32 = socket->handle};
     82     if (mask & 1) event.events |= EPOLLIN;
     83     if (mask & 32) event.events |= EPOLLRDHUP;
     84     if (epoll_ctl(socket_events, socket->watched ? EPOLL_CTL_MOD : EPOLL_CTL_ADD, socket->descriptor, &event)) abort();
     85     socket->watched = 1;
     86 }
     87 
     88 static void stop_socket_events_locked(struct guest_socket *socket)
     89 {
     90     socket->selected = socket->armed = socket->recorded = 0;
     91     arm_socket_events_locked(socket);
     92     if (socket->event) linux_sync_event_release(socket->event);
     93     socket->event = NULL;
     94 }
     95 
     96 static void record_socket_event_locked(struct guest_socket *socket, uint32_t mask, uint32_t error)
     97 {
     98     socket->recorded |= mask;
     99     socket->armed &= ~mask;
    100     if (mask == 32) socket->close_error = error;
    101     if (socket->event) linux_sync_event_change(socket->event, 1);
    102 }
    103 
    104 static void *watch_socket_events(void *argument)
    105 {
    106     for (;;) {
    107         struct epoll_event events[16];
    108         int count = epoll_wait(socket_events, events, 16, -1);
    109         if (count < 0) { if (errno == EINTR) continue; abort(); }
    110         if (pthread_mutex_lock(&socket_mutex)) abort();
    111         for (int i = 0; i < count; ++i) {
    112             struct guest_socket *socket;
    113             for (socket = sockets; socket; socket = socket->next)
    114                 if (socket->handle == events[i].data.u32) break;
    115             if (!socket || !socket->selected) continue;
    116 
    117             /* Preserve errors consumed by the monitor for the guest's next recv. */
    118             if (events[i].events & EPOLLERR) {
    119                 int error;
    120                 socklen_t size = sizeof(error);
    121                 if (getsockopt(socket->descriptor, SOL_SOCKET, SO_ERROR, &error, &size)) abort();
    122                 if (error) socket->receive_error = socket_error(error);
    123             }
    124 
    125             /* Data and FIN may be reported together; a FIN alone is not FD_READ. */
    126             unsigned char byte;
    127             int result = recv(socket->descriptor, &byte, 1, MSG_PEEK | MSG_DONTWAIT);
    128             int would_block = result < 0 && errno == EAGAIN;
    129             if (result < 0 && !would_block) socket->receive_error = socket_error(errno);
    130             if (!result || socket->receive_error || (events[i].events & (EPOLLRDHUP | EPOLLHUP))) {
    131                 if (!socket->receive_error) socket->shutdown |= 4;
    132                 if (socket->armed & 32) record_socket_event_locked(socket, 32, socket->receive_error);
    133             }
    134             if (result > 0 && (socket->armed & 1)) record_socket_event_locked(socket, 1, 0);
    135             if (result > 0 || would_block) arm_socket_events_locked(socket);
    136         }
    137         if (pthread_mutex_unlock(&socket_mutex)) abort();
    138     }
    139     return NULL;
    140 }
    141 
    142 static void event_select_socket(void)
    143 {
    144     uint32_t handle = MEM32(g_esp + 4), event_handle = MEM32(g_esp + 8), mask = MEM32(g_esp + 12);
    145     g_esp += 16;
    146     g_eax = UINT32_MAX;
    147     if (pthread_mutex_lock(&socket_mutex)) abort();
    148     struct guest_socket *socket = find_socket_locked(handle);
    149     if (socket) {
    150         if (mask & ~0x21u) {
    151             fprintf(stderr, "Unsupported WSAEventSelect mask: %08x\n", mask);
    152             abort();
    153         }
    154         struct semaphore_handle *event = mask && event_handle ? linux_sync_event_acquire(event_handle) : NULL;
    155         if (mask && event_handle && !event) MEM32(g_fs_base + 0x34) = 10022;
    156         else {
    157             /* The reached AO path registers READ/CLOSE after its TCP connect succeeds. */
    158             if (mask) {
    159                 struct sockaddr_in peer;
    160                 socklen_t size = sizeof(peer);
    161                 int type;
    162                 if (getpeername(socket->descriptor, (struct sockaddr *)&peer, &size)) {
    163                     fprintf(stderr, "Socket events before connection are not implemented\n");
    164                     abort();
    165                 }
    166                 size = sizeof(type);
    167                 if (getsockopt(socket->descriptor, SOL_SOCKET, SO_TYPE, &type, &size) || type != SOCK_STREAM) abort();
    168             }
    169             int nonblocking = 1;
    170             if (ioctl(socket->descriptor, FIONBIO, &nonblocking)) abort();
    171             if (mask && socket_events < 0) {
    172                 socket_events = epoll_create1(EPOLL_CLOEXEC);
    173                 pthread_t thread;
    174                 if (socket_events < 0 || pthread_create(&thread, NULL, watch_socket_events, NULL) || pthread_detach(thread)) abort();
    175             }
    176             stop_socket_events_locked(socket);
    177             socket->event = event;
    178             socket->selected = socket->armed = mask;
    179             socket->close_error = 0;
    180             arm_socket_events_locked(socket);
    181             MEM32(g_fs_base + 0x34) = 0;
    182             g_eax = 0;
    183         }
    184     }
    185     if (pthread_mutex_unlock(&socket_mutex)) abort();
    186 }
    187 
    188 static void enum_socket_events(void)
    189 {
    190     uint32_t handle = MEM32(g_esp + 4), event_handle = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
    191     g_esp += 16;
    192     g_eax = UINT32_MAX;
    193     if (pthread_mutex_lock(&socket_mutex)) abort();
    194     struct guest_socket *socket = find_socket_locked(handle);
    195     if (socket) {
    196         if (!output) MEM32(g_fs_base + 0x34) = 10014;
    197         else {
    198             struct semaphore_handle *event = event_handle ? linux_sync_event_acquire(event_handle) : NULL;
    199             if (event_handle && !event) MEM32(g_fs_base + 0x34) = 10022;
    200             else {
    201                 MEM32(output) = socket->recorded;
    202                 if (socket->recorded & 1) MEM32(output + 4) = 0;
    203                 if (socket->recorded & 32) MEM32(output + 24) = socket->close_error;
    204                 socket->recorded = 0;
    205                 if (event) {
    206                     linux_sync_event_change(event, 0);
    207                     linux_sync_event_release(event);
    208                 }
    209                 MEM32(g_fs_base + 0x34) = 0;
    210                 g_eax = 0;
    211             }
    212         }
    213     }
    214     if (pthread_mutex_unlock(&socket_mutex)) abort();
    215 }
    216 
    217 static void create_socket(void)
    218 {
    219     int family = MEM32(g_esp + 4), type = MEM32(g_esp + 8), protocol = MEM32(g_esp + 12);
    220     g_esp += 16;
    221     g_eax = UINT32_MAX;
    222     if (pthread_mutex_lock(&socket_mutex)) abort();
    223     uint32_t error = 0;
    224     if (!startup_count) error = 10093;
    225     else if (family != 2 || (type != 1 && type != 2) || (protocol && protocol != 6 && protocol != 17)) {
    226         fprintf(stderr, "Unsupported socket family/type/protocol: %d/%d/%d\n", family, type, protocol);
    227         abort();
    228     } else {
    229         int descriptor = socket(AF_INET, type == 1 ? SOCK_STREAM : SOCK_DGRAM, protocol);
    230         if (descriptor < 0) error = socket_error(errno);
    231         else {
    232             struct guest_socket *socket = malloc(sizeof(*socket));
    233             if (!socket || next_handle >= 0x0a000000u) abort();
    234             *socket = (struct guest_socket){.handle = next_handle, .descriptor = descriptor, .next = sockets};
    235             sockets = socket;
    236             next_handle += 4;
    237             g_eax = socket->handle;
    238         }
    239     }
    240     MEM32(g_fs_base + 0x34) = error;
    241     if (pthread_mutex_unlock(&socket_mutex)) abort();
    242 }
    243 
    244 static void close_socket(void)
    245 {
    246     uint32_t handle = MEM32(g_esp + 4);
    247     g_esp += 8;
    248     g_eax = UINT32_MAX;
    249     if (pthread_mutex_lock(&socket_mutex)) abort();
    250     struct guest_socket *socket = find_socket_locked(handle);
    251     if (socket) {
    252         stop_socket_events_locked(socket);
    253         if (close(socket->descriptor)) MEM32(g_fs_base + 0x34) = socket_error(errno);
    254         else {
    255             struct guest_socket **link = &sockets;
    256             while (*link != socket) link = &(*link)->next;
    257             *link = socket->next;
    258             free(socket);
    259             MEM32(g_fs_base + 0x34) = 0;
    260             g_eax = 0;
    261         }
    262     }
    263     if (pthread_mutex_unlock(&socket_mutex)) abort();
    264 }
    265 
    266 static void control_socket(void)
    267 {
    268     uint32_t handle = MEM32(g_esp + 4), command = MEM32(g_esp + 8), argument = MEM32(g_esp + 12);
    269     g_esp += 16;
    270     g_eax = UINT32_MAX;
    271     if (pthread_mutex_lock(&socket_mutex)) abort();
    272     struct guest_socket *socket = find_socket_locked(handle);
    273     if (socket) {
    274         if (!argument) MEM32(g_fs_base + 0x34) = 10014;
    275         else if (command == 0x8004667eu && !MEM32(argument) && socket->selected)
    276             MEM32(g_fs_base + 0x34) = 10022;
    277         else {
    278             unsigned long request;
    279             if (command == 0x8004667eu) request = FIONBIO;
    280             else if (command == 0x4004667fu) request = FIONREAD;
    281             else {
    282                 fprintf(stderr, "Unsupported ioctlsocket command: %08x\n", command);
    283                 abort();
    284             }
    285             int value = request == FIONBIO ? MEM32(argument) != 0 : 0;
    286             if (ioctl(socket->descriptor, request, &value)) MEM32(g_fs_base + 0x34) = socket_error(errno);
    287             else {
    288                 if (request == FIONREAD) MEM32(argument) = value;
    289                 MEM32(g_fs_base + 0x34) = 0;
    290                 g_eax = 0;
    291             }
    292         }
    293     }
    294     if (pthread_mutex_unlock(&socket_mutex)) abort();
    295 }
    296 
    297 static void network_long(void)
    298 {
    299     g_eax = htonl(MEM32(g_esp + 4));
    300     g_esp += 8;
    301 }
    302 
    303 static int socket_descriptor(uint32_t handle, unsigned direction)
    304 {
    305     /* Hold a descriptor reference across the potentially blocking native call. */
    306     if (pthread_mutex_lock(&socket_mutex)) abort();
    307     struct guest_socket *socket = find_socket_locked(handle);
    308     if (socket && (socket->shutdown & direction)) {
    309         MEM32(g_fs_base + 0x34) = 10058;
    310         socket = NULL;
    311     }
    312     if (socket && direction == 1 && socket->receive_error) {
    313         int unread;
    314         if (ioctl(socket->descriptor, FIONREAD, &unread)) abort();
    315         if (!unread) {
    316             MEM32(g_fs_base + 0x34) = socket->receive_error;
    317             socket = NULL;
    318         }
    319     }
    320     int descriptor = socket ? fcntl(socket->descriptor, F_DUPFD_CLOEXEC, 0) : -1;
    321     if (socket && descriptor < 0) MEM32(g_fs_base + 0x34) = socket_error(errno);
    322     if (pthread_mutex_unlock(&socket_mutex)) abort();
    323     return descriptor;
    324 }
    325 
    326 static void connect_socket(void)
    327 {
    328     uint32_t handle = MEM32(g_esp + 4), address = MEM32(g_esp + 8);
    329     int32_t length = MEM32(g_esp + 12);
    330     g_esp += 16;
    331     g_eax = UINT32_MAX;
    332     int descriptor = socket_descriptor(handle, 0);
    333     if (descriptor < 0) return;
    334 
    335     uint32_t error = 0;
    336     if (!address || length < 16) error = 10014;
    337     else if (MEM16(address) != 2) error = 10047;
    338     else {
    339         struct sockaddr_in native = {0};
    340         native.sin_family = AF_INET;
    341         native.sin_port = MEM16(address + 2);
    342         native.sin_addr.s_addr = MEM32(address + 4);
    343         if (connect(descriptor, (struct sockaddr *)&native, sizeof(native))) error = socket_error(errno);
    344     }
    345     if (close(descriptor)) abort();
    346     if (pthread_mutex_lock(&socket_mutex)) abort();
    347     for (struct guest_socket *socket = sockets; socket; socket = socket->next)
    348         if (socket->handle == handle) { socket->connecting = error == 10035; break; }
    349     if (pthread_mutex_unlock(&socket_mutex)) abort();
    350     MEM32(g_fs_base + 0x34) = error;
    351     g_eax = error ? UINT32_MAX : 0;
    352 }
    353 
    354 static void socket_address(int peer)
    355 {
    356     uint32_t handle = MEM32(g_esp + 4), output = MEM32(g_esp + 8), length = MEM32(g_esp + 12);
    357     g_esp += 16;
    358     g_eax = UINT32_MAX;
    359     int descriptor = socket_descriptor(handle, 0);
    360     if (descriptor < 0) return;
    361     uint32_t error = 0;
    362     if (!output || !length || (int32_t)MEM32(length) < 16) error = 10014;
    363     else {
    364         struct sockaddr_in address = {0};
    365         socklen_t size = sizeof(address);
    366         int result = peer ? getpeername(descriptor, (struct sockaddr *)&address, &size) :
    367                             getsockname(descriptor, (struct sockaddr *)&address, &size);
    368         if (result) error = socket_error(errno);
    369         else if (!peer && !address.sin_port) error = 10022; /* Winsock rejects unbound sockets. */
    370         else {
    371             if (address.sin_family != AF_INET) abort();
    372             MEM16(output) = 2;
    373             MEM16(output + 2) = address.sin_port;
    374             MEM32(output + 4) = address.sin_addr.s_addr;
    375             memset((void *)ADDR(output + 8), 0, 8);
    376             MEM32(length) = 16;
    377             g_eax = 0;
    378         }
    379     }
    380     if (close(descriptor)) abort();
    381     MEM32(g_fs_base + 0x34) = error;
    382 }
    383 
    384 static void local_socket_address(void) { socket_address(0); }
    385 static void peer_socket_address(void) { socket_address(1); }
    386 
    387 static uint32_t finish_socket_read(uint32_t handle, int32_t length, uint32_t error)
    388 {
    389     if (pthread_mutex_lock(&socket_mutex)) abort();
    390     for (struct guest_socket *socket = sockets; socket; socket = socket->next) {
    391         if (socket->handle != handle) continue;
    392         /* The monitor and recv may observe a reset in either order. */
    393         if (error == 10053 || error == 10054 || error == 10060) socket->receive_error = error;
    394         if (length && (g_eax == 0 || g_eax == UINT32_MAX) && socket->receive_error) {
    395             error = socket->receive_error;
    396             g_eax = UINT32_MAX;
    397         }
    398         socket->armed |= socket->selected & 1;
    399         arm_socket_events_locked(socket);
    400         break;
    401     }
    402     if (pthread_mutex_unlock(&socket_mutex)) abort();
    403     return error;
    404 }
    405 
    406 static void transfer_socket(int sending)
    407 {
    408     uint32_t handle = MEM32(g_esp + 4), buffer = MEM32(g_esp + 8), flags = MEM32(g_esp + 16);
    409     int32_t length = MEM32(g_esp + 12);
    410     g_esp += 20;
    411     g_eax = UINT32_MAX;
    412     int descriptor = socket_descriptor(handle, sending ? 2 : 1);
    413     if (descriptor < 0) return;
    414     uint32_t error = 0;
    415     if (!buffer || length < 0) error = 10014;
    416     else {
    417         if (flags && (sending || flags != 2)) {
    418             fprintf(stderr, "Unsupported socket %s flags: %08x\n", sending ? "send" : "recv", flags);
    419             abort();
    420         }
    421         int result = sending ? send(descriptor, (void *)ADDR(buffer), length, MSG_NOSIGNAL) :
    422                                recv(descriptor, (void *)ADDR(buffer), length, flags ? MSG_PEEK : 0);
    423         if (result < 0) error = socket_error(errno);
    424         else {
    425             g_eax = result;
    426             if (!sending && !result && length) {
    427                 int type;
    428                 socklen_t size = sizeof(type);
    429                 if (getsockopt(descriptor, SOL_SOCKET, SO_TYPE, &type, &size)) abort();
    430                 if (type == SOCK_STREAM) {
    431                     if (pthread_mutex_lock(&socket_mutex)) abort();
    432                     for (struct guest_socket *socket = sockets; socket; socket = socket->next)
    433                         if (socket->handle == handle) { socket->shutdown |= 4; break; }
    434                     if (pthread_mutex_unlock(&socket_mutex)) abort();
    435                 }
    436             }
    437         }
    438     }
    439     if (close(descriptor)) abort();
    440     if (!sending && buffer && length >= 0) error = finish_socket_read(handle, length, error);
    441     MEM32(g_fs_base + 0x34) = error;
    442 }
    443 
    444 static void send_socket(void) { transfer_socket(1); }
    445 static void receive_socket(void) { transfer_socket(0); }
    446 
    447 static void shutdown_socket(void)
    448 {
    449     uint32_t handle = MEM32(g_esp + 4), how = MEM32(g_esp + 8);
    450     g_esp += 12;
    451     g_eax = UINT32_MAX;
    452     if (pthread_mutex_lock(&socket_mutex)) abort();
    453     struct guest_socket *socket = find_socket_locked(handle);
    454     if (socket) {
    455         if (how > 2) MEM32(g_fs_base + 0x34) = 10022;
    456         else {
    457             int result = shutdown(socket->descriptor, how == 0 ? SHUT_RD : how == 1 ? SHUT_WR : SHUT_RDWR);
    458             /* Linux discards the TCP connection after both FINs; Winsock still accepts shutdown. */
    459             if (result && !(errno == ENOTCONN && (socket->shutdown & 4)))
    460                 MEM32(g_fs_base + 0x34) = socket_error(errno);
    461             else {
    462                 socket->shutdown |= how == 0 ? 1 : how == 1 ? 2 : 3;
    463                 MEM32(g_fs_base + 0x34) = 0;
    464                 g_eax = 0;
    465             }
    466         }
    467     }
    468     if (pthread_mutex_unlock(&socket_mutex)) abort();
    469 }
    470 
    471 static void select_sockets(void)
    472 {
    473     uint32_t sets[] = {MEM32(g_esp + 8), MEM32(g_esp + 12), MEM32(g_esp + 16)};
    474     uint32_t timeout = MEM32(g_esp + 20), counts[3], total = 0, error = 0;
    475     int64_t deadline = 0;
    476     g_esp += 24;
    477     g_eax = UINT32_MAX;
    478     if (pthread_mutex_lock(&socket_mutex)) abort();
    479     if (!startup_count) error = 10093;
    480     if (pthread_mutex_unlock(&socket_mutex)) abort();
    481     if (error) { MEM32(g_fs_base + 0x34) = error; return; }
    482 
    483     /* Winsock uses arrays of 32-bit handles and an unchanged 32-bit timeval. */
    484     if (timeout) {
    485         int32_t seconds = MEM32(timeout), micros = MEM32(timeout + 4);
    486         if (seconds < 0 || micros < 0) { MEM32(g_fs_base + 0x34) = 10022; return; }
    487         struct timespec now;
    488         if (clock_gettime(CLOCK_MONOTONIC, &now)) abort();
    489         deadline = (int64_t)now.tv_sec * 1000000000 + now.tv_nsec +
    490                    (int64_t)seconds * 1000000000 + (int64_t)micros * 1000;
    491     }
    492     for (unsigned set = 0; set < 3; ++set) {
    493         counts[set] = sets[set] ? MEM32(sets[set]) : 0;
    494         if (counts[set] > UINT32_MAX - total) abort();
    495         total += counts[set];
    496     }
    497     if (!total) { MEM32(g_fs_base + 0x34) = 10022; return; }
    498     struct pollfd *polls = calloc(total, sizeof(*polls));
    499     struct select_entry { uint32_t handle; int descriptor, connecting, ready; };
    500     struct select_entry *entries = calloc(total, sizeof(*entries));
    501     if (!polls || !entries) abort();
    502     unsigned acquired = 0;
    503     if (pthread_mutex_lock(&socket_mutex)) abort();
    504     for (unsigned set = 0; set < 3 && !error; ++set) {
    505         for (unsigned i = 0; i < counts[set]; ++i) {
    506             uint32_t handle = MEM32(sets[set] + 4 + i * 4);
    507             struct guest_socket *socket = find_socket_locked(handle);
    508             if (!socket) { error = MEM32(g_fs_base + 0x34); break; }
    509             int descriptor = fcntl(socket->descriptor, F_DUPFD_CLOEXEC, 0);
    510             if (descriptor < 0) { error = socket_error(errno); break; }
    511             entries[acquired] = (struct select_entry){handle, descriptor, socket->connecting, 0};
    512             polls[acquired++] = (struct pollfd){descriptor, set == 0 ? POLLIN : set == 1 ? POLLOUT : POLLPRI, 0};
    513         }
    514     }
    515     if (pthread_mutex_unlock(&socket_mutex)) abort();
    516 
    517     /* poll reports failed connects as writable; Winsock reports them in exceptfds. */
    518     unsigned ready = 0;
    519     while (!error) {
    520         struct timespec remaining;
    521         if (timeout) {
    522             struct timespec now;
    523             if (clock_gettime(CLOCK_MONOTONIC, &now)) abort();
    524             int64_t nanos = deadline - ((int64_t)now.tv_sec * 1000000000 + now.tv_nsec);
    525             if (nanos < 0) nanos = 0;
    526             remaining = (struct timespec){nanos / 1000000000, nanos % 1000000000};
    527         }
    528         int result = ppoll(polls, total, timeout ? &remaining : NULL, NULL);
    529         if (result < 0) { error = socket_error(errno); break; }
    530         if (!result) break;
    531         unsigned index = 0;
    532         for (unsigned set = 0; set < 3; ++set) {
    533             for (unsigned i = 0; i < counts[set]; ++i, ++index) {
    534                 int events = polls[index].revents;
    535                 if (!events) continue;
    536                 int failed_connect = 0;
    537                 if (entries[index].connecting) {
    538                     struct sockaddr_in peer;
    539                     socklen_t length = sizeof(peer);
    540                     failed_connect = getpeername(entries[index].descriptor, (struct sockaddr *)&peer, &length) != 0;
    541                     if (!failed_connect) {
    542                         entries[index].connecting = 0;
    543                         if (pthread_mutex_lock(&socket_mutex)) abort();
    544                         for (struct guest_socket *socket = sockets; socket; socket = socket->next)
    545                             if (socket->handle == entries[index].handle) { socket->connecting = 0; break; }
    546                         if (pthread_mutex_unlock(&socket_mutex)) abort();
    547                     }
    548                 }
    549                 entries[index].ready = failed_connect ? set == 2 :
    550                     set == 0 ? (events & (POLLIN | POLLHUP | POLLERR)) != 0 :
    551                     set == 1 ? (events & POLLOUT) != 0 : (events & POLLPRI) != 0;
    552                 ready += entries[index].ready;
    553                 /* Ignore an unrequested failed connection until another event/timeout. */
    554                 if (!entries[index].ready && (failed_connect || (events & (POLLHUP | POLLERR)))) polls[index].fd = -1;
    555             }
    556         }
    557         if (ready) break;
    558     }
    559     if (!error) {
    560         unsigned index = 0;
    561         for (unsigned set = 0; set < 3; ++set) {
    562             unsigned count = 0;
    563             for (unsigned i = 0; i < counts[set]; ++i, ++index)
    564                 if (entries[index].ready) MEM32(sets[set] + 4 + count++ * 4) = entries[index].handle;
    565             if (sets[set]) MEM32(sets[set]) = count;
    566         }
    567         g_eax = ready;
    568     }
    569     for (unsigned i = 0; i < acquired; ++i)
    570         if (close(entries[i].descriptor)) abort();
    571     free(entries);
    572     free(polls);
    573     MEM32(g_fs_base + 0x34) = error;
    574 }
    575 
    576 static void network_short(void)
    577 {
    578     g_eax = htons((uint16_t)MEM32(g_esp + 4));
    579     g_esp += 8;
    580 }
    581 
    582 static void address_string(void)
    583 {
    584     struct in_addr address = {MEM32(g_esp + 4)};
    585     /* The returned string belongs to the guest thread, not libc's host TLS. */
    586     g_eax = g_fs_base + 0x2100;
    587     if (!inet_ntop(AF_INET, &address, (char *)ADDR(g_eax), 16)) abort();
    588     MEM32(g_fs_base + 0x34) = 0;
    589     g_esp += 8;
    590 }
    591 
    592 static void socket_in_set(void)
    593 {
    594     uint32_t handle = MEM32(g_esp + 4), set = MEM32(g_esp + 8);
    595     g_eax = 0;
    596     for (uint32_t i = 0; i < MEM32(set); ++i) {
    597         if (MEM32(set + 4 + i * 4) == handle) { g_eax = 1; break; }
    598     }
    599     g_esp += 12;
    600 }
    601 
    602 static void wsa_startup(void)
    603 {
    604     if (pthread_mutex_lock(&socket_mutex)) abort();
    605     uint16_t requested = MEM32(g_esp + 4);
    606     uint32_t data = MEM32(g_esp + 8);
    607     uint16_t version = 0x0202;
    608     if ((requested & 0xff) == 1) version = requested >> 8 ? 0x0101 : 1;
    609     else if ((requested & 0xff) == 2 && (requested >> 8) < 2) version = requested;
    610     g_eax = 10014; /* WSAEFAULT */
    611     if (data) {
    612         /* WSADATA is 400 bytes on x86; padding and lpVendorInfo remain untouched. */
    613         MEM16(data) = version;
    614         MEM16(data + 2) = 0x0202;
    615         strcpy((char *)ADDR(data + 4), "WinSock 2.0");
    616         strcpy((char *)ADDR(data + 261), "Running");
    617         MEM16(data + 390) = (version & 0xff) == 1 ? 32767 : 0;
    618         MEM16(data + 392) = (version & 0xff) == 1 ? 65467 : 0;
    619         g_eax = 10092; /* WSAVERNOTSUPPORTED */
    620         if (requested & 0xff) {
    621             if (!startup_count) MEM32(g_fs_base + 0x34) = 0;
    622             ++startup_count;
    623             g_eax = 0;
    624         }
    625     }
    626     g_esp += 12;
    627     if (pthread_mutex_unlock(&socket_mutex)) abort();
    628 }
    629 
    630 static void wsa_cleanup(void)
    631 {
    632     if (pthread_mutex_lock(&socket_mutex)) abort();
    633     g_eax = UINT32_MAX;
    634     if (startup_count) {
    635         --startup_count;
    636         if (!startup_count) {
    637             while (sockets) {
    638                 struct guest_socket *socket = sockets;
    639                 sockets = socket->next;
    640                 stop_socket_events_locked(socket);
    641                 if (close(socket->descriptor)) abort();
    642                 free(socket);
    643             }
    644         }
    645         MEM32(g_fs_base + 0x34) = 0;
    646         g_eax = 0;
    647     } else MEM32(g_fs_base + 0x34) = 10093; /* WSANOTINITIALISED */
    648     g_esp += 4;
    649     if (pthread_mutex_unlock(&socket_mutex)) abort();
    650 }
    651 
    652 static void wsa_get_last_error(void)
    653 {
    654     g_eax = MEM32(g_fs_base + 0x34);
    655     g_esp += 4;
    656 }
    657 
    658 static void wsa_set_last_error(void)
    659 {
    660     MEM32(g_fs_base + 0x34) = MEM32(g_esp + 4);
    661     g_esp += 8;
    662 }
    663 
    664 static void host_name(void)
    665 {
    666     if (pthread_mutex_lock(&socket_mutex)) abort();
    667     uint32_t output = MEM32(g_esp + 4);
    668     int32_t size = MEM32(g_esp + 8);
    669     char name[256];
    670     uint32_t error = 0;
    671     if (!startup_count) error = 10093; /* WSANOTINITIALISED */
    672     else if (!output || size <= 0) error = 10014; /* WSAEFAULT */
    673     else if (gethostname(name, sizeof(name))) error = 10050; /* WSAENETDOWN */
    674     else if ((size_t)size <= strlen(name)) error = 10014;
    675     else memcpy((void *)ADDR(output), name, strlen(name) + 1);
    676 
    677     MEM32(g_fs_base + 0x34) = error;
    678     g_eax = error ? UINT32_MAX : 0;
    679     g_esp += 12;
    680     if (pthread_mutex_unlock(&socket_mutex)) abort();
    681 }
    682 
    683 recomp_func_t linux_network_lookup(const char *name, uint32_t ordinal)
    684 {
    685     static const struct { const char *name; uint32_t ordinal; recomp_func_t function; } functions[] = {
    686         {"WSAStartup", 115, wsa_startup}, {"WSACleanup", 116, wsa_cleanup},
    687         {"WSAGetLastError", 111, wsa_get_last_error}, {"WSASetLastError", 112, wsa_set_last_error},
    688         {"gethostname", 57, host_name},
    689         {"htonl", 8, network_long}, {"htons", 9, network_short},
    690         {"ntohl", 14, network_long}, {"ntohs", 15, network_short},
    691         {"inet_ntoa", 12, address_string},
    692         {"socket", 23, create_socket}, {"closesocket", 3, close_socket},
    693         {"ioctlsocket", 10, control_socket},
    694         {"connect", 4, connect_socket},
    695         {"__WSAFDIsSet", 151, socket_in_set},
    696         {"select", 18, select_sockets},
    697         {"send", 19, send_socket}, {"recv", 16, receive_socket},
    698         {"shutdown", 22, shutdown_socket},
    699         {"getsockname", 6, local_socket_address}, {"getpeername", 5, peer_socket_address},
    700         {"WSAEventSelect", 0, event_select_socket}, {"WSAEnumNetworkEvents", 0, enum_socket_events},
    701     };
    702     for (unsigned i = 0; i < sizeof(functions) / sizeof(functions[0]); ++i)
    703         if (name ? !strcmp(name, functions[i].name) : ordinal && ordinal == functions[i].ordinal)
    704             return functions[i].function;
    705     return NULL;
    706 }