win32_wsiocp.c 14.3 KB
Newer Older
H
Henry Rawas 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * Copyright (c), Microsoft Open Technologies, Inc.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "win32fixes.h"
24 25 26
#include "..\ae.h"
#include "..\adlist.h"
#include "..\zmalloc.h"
H
Henry Rawas 已提交
27 28 29
#include <mswsock.h>
#include <Guiddef.h>
#include "win32_wsiocp.h"
30
#include "Win32_FDAPI.h"
31
#include <errno.h>
H
Henry Rawas 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46


static void *iocpState;
static HANDLE iocph;
static fnGetSockState * aeGetSockState;
static fnDelSockState * aeDelSockState;

#define SUCCEEDED_WITH_IOCP(result)                        \
  ((result) || (GetLastError() == ERROR_IO_PENDING))

/* for zero length reads use shared buf */
static DWORD wsarecvflags;
static char zreadchar[1];


47
int aeWinQueueAccept(int listenfd) {
H
Henry Rawas 已提交
48 49 50
    aeSockState *sockstate;
    aeSockState *accsockstate;
    DWORD result, bytes;
51
    int acceptfd;
H
Henry Rawas 已提交
52 53
    aacceptreq * areq;

54
    if ((sockstate = aeGetSockState(iocpState, listenfd)) == NULL) {
H
Henry Rawas 已提交
55 56 57 58
        errno = WSAEINVAL;
        return -1;
    }

59 60
    acceptfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (acceptfd == -1) {
H
Henry Rawas 已提交
61 62 63
        errno = WSAEINVAL;
        return -1;
    }
64

65
    accsockstate = aeGetSockState(iocpState, acceptfd);
H
Henry Rawas 已提交
66 67 68 69 70 71 72 73 74 75
    if (accsockstate == NULL) {
        errno = WSAEINVAL;
        return -1;
    }

    accsockstate->masks = SOCKET_ATTACHED;
    /* keep accept socket in buf len until accepted */
    areq = (aacceptreq *)zmalloc(sizeof(aacceptreq));
    memset(areq, 0, sizeof(aacceptreq));
    areq->buf = (char *)zmalloc(sizeof(struct sockaddr_storage) * 2 + 64);
76
    areq->accept = acceptfd;
H
Henry Rawas 已提交
77 78
    areq->next = NULL;

79
    result = FDAPI_AcceptEx(listenfd, acceptfd,
H
Henry Rawas 已提交
80 81 82 83 84 85 86 87 88
                            areq->buf, 0,
                            sizeof(struct sockaddr_storage),
                            sizeof(struct sockaddr_storage),
                            &bytes, &areq->ov);
    if (SUCCEEDED_WITH_IOCP(result)){
        sockstate->masks |= ACCEPT_PENDING;
    } else {
        errno = WSAGetLastError();
        sockstate->masks &= ~ACCEPT_PENDING;
89
        close(acceptfd);
H
Henry Rawas 已提交
90 91 92 93 94 95 96 97 98
        accsockstate->masks = 0;
        zfree(areq);
        return -1;
    }

    return TRUE;
}

/* listen using extension function to get faster accepts */
99
int aeWinListen(int rfd, int backlog) {
H
Henry Rawas 已提交
100 101 102 103
    aeSockState *sockstate;
    const GUID wsaid_acceptex = WSAID_ACCEPTEX;
    const GUID wsaid_acceptexaddrs = WSAID_GETACCEPTEXSOCKADDRS;

104
    if ((sockstate = aeGetSockState(iocpState, rfd)) == NULL) {
H
Henry Rawas 已提交
105 106 107 108
        errno = WSAEINVAL;
        return SOCKET_ERROR;
    }

109
    aeWinSocketAttach(rfd);
H
Henry Rawas 已提交
110 111
    sockstate->masks |= LISTEN_SOCK;

112 113
    if (listen(rfd, backlog) == 0) {
        if (aeWinQueueAccept(rfd) == -1) {
114
            errno = WSAGetLastError();
H
Henry Rawas 已提交
115 116
            return SOCKET_ERROR;
        }
117 118
    } else {
        errno = WSAGetLastError();
H
Henry Rawas 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    }

    return 0;
}

/* return the queued accept socket */
int aeWinAccept(int fd, struct sockaddr *sa, socklen_t *len) {
    aeSockState *sockstate;
    int acceptsock;
    int result;
    SOCKADDR *plocalsa;
    SOCKADDR *premotesa;
    int locallen, remotelen;
    aacceptreq * areq;

    if ((sockstate = aeGetSockState(iocpState, fd)) == NULL) {
        errno = WSAEINVAL;
        return SOCKET_ERROR;
    }


    areq = sockstate->reqs;
    if (areq == NULL) {
142
        errno = EWOULDBLOCK;
H
Henry Rawas 已提交
143 144 145 146 147 148 149
        return SOCKET_ERROR;
    }

    sockstate->reqs = areq->next;

    acceptsock = (int)areq->accept;

150
    result = FDAPI_UpdateAcceptContext(acceptsock);
H
Henry Rawas 已提交
151 152 153 154 155 156
    if (result == SOCKET_ERROR) {
        errno = WSAGetLastError();
        return SOCKET_ERROR;
    }

    locallen = *len;
157 158 159
    FDAPI_GetAcceptExSockaddrs(
                    acceptsock,
                    areq->buf,
H
Henry Rawas 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
                    0,
                    sizeof(struct sockaddr_storage),
                    sizeof(struct sockaddr_storage),
                    &plocalsa, &locallen,
                    &premotesa, &remotelen);

    locallen = remotelen < *len ? remotelen : *len;
    memcpy(sa, premotesa, locallen);
    *len = locallen;

    aeWinSocketAttach(acceptsock);

    zfree(areq->buf);
    zfree(areq);

    /* queue another accept */
176
    if (aeWinQueueAccept(fd) == -1) {
H
Henry Rawas 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190
        return SOCKET_ERROR;
    }

    return acceptsock;
}


/* after doing read caller needs to call done
 * so that we can continue to check for read events.
 * This is not necessary if caller will delete read events */
int aeWinReceiveDone(int fd) {
    aeSockState *sockstate;
    int result;
    WSABUF zreadbuf;
191
    DWORD bytesReceived = 0;
H
Henry Rawas 已提交
192 193 194 195 196 197 198 199 200 201 202 203

    if ((sockstate = aeGetSockState(iocpState, fd)) == NULL) {
        errno = WSAEINVAL;
        return -1;
    }
    if ((sockstate->masks & SOCKET_ATTACHED) == 0) {
        return 0;
    }

    /* use zero length read with overlapped to get notification
     of when data is available */
    memset(&sockstate->ov_read, 0, sizeof(sockstate->ov_read));
204
    wsarecvflags = 0;
H
Henry Rawas 已提交
205 206 207

    zreadbuf.buf = zreadchar;
    zreadbuf.len = 0;
208
    result = WSARecv(fd,
H
Henry Rawas 已提交
209 210
                     &zreadbuf,
                     1,
211
                     &bytesReceived,
H
Henry Rawas 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
                     &wsarecvflags,
                     &sockstate->ov_read,
                     NULL);
    if (SUCCEEDED_WITH_IOCP(result == 0)){
        sockstate->masks |= READ_QUEUED;
    } else {
        errno = WSAGetLastError();
        sockstate->masks &= ~READ_QUEUED;
        return -1;
    }
    return 0;
}

/* wrapper for send
 * enables use of WSA Send to get IOCP notification of completion.
 * returns -1  with errno = WSA_IO_PENDING if callback will be invoked later */
228
int aeWinSocketSend(int fd, char *buf, int len, 
H
Henry Rawas 已提交
229 230 231 232
                    void *eventLoop, void *client, void *data, void *proc) {
    aeSockState *sockstate;
    int result;
    asendreq *areq;
233
    DWORD bytesSent = 0;
H
Henry Rawas 已提交
234 235

    sockstate = aeGetSockState(iocpState, fd);
236 237 238 239 240 241

    if (sockstate != NULL &&
        (sockstate->masks & CONNECT_PENDING)) {
        aeWait(fd, AE_WRITABLE, 50);
    }

H
Henry Rawas 已提交
242 243 244 245
    /* if not an async socket, do normal send */
    if (sockstate == NULL ||
        (sockstate->masks & SOCKET_ATTACHED) == 0 ||
        proc == NULL) {
246
        result = write(fd, buf, len);
H
Henry Rawas 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
        if (result == SOCKET_ERROR) {
            errno = WSAGetLastError();
        }
        return result;
    }

    /* use overlapped structure to send using IOCP */
    areq = (asendreq *)zmalloc(sizeof(asendreq));
    memset(areq, 0, sizeof(asendreq));
    areq->wbuf.len = len;
    areq->wbuf.buf = buf;
    areq->eventLoop = (aeEventLoop *)eventLoop;
    areq->req.client = client;
    areq->req.data = data;
    areq->req.len = len;
    areq->req.buf = buf;
    areq->proc = (aeFileProc *)proc;

265
    result = WSASend(fd,
H
Henry Rawas 已提交
266 267
                    &areq->wbuf,
                    1,
268
                    &bytesSent,
269
                    0,
H
Henry Rawas 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283
                    &areq->ov,
                    NULL);

    if (SUCCEEDED_WITH_IOCP(result == 0)){
        errno = WSA_IO_PENDING;
        sockstate->wreqs++;
        listAddNodeTail(&sockstate->wreqlist, areq);
    } else {
        errno = WSAGetLastError();
        zfree(areq);
    }
    return SOCKET_ERROR;
}

284 285 286



287
/* for non-blocking connect with IOCP */
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
int aeWinSocketConnect(int fd, const SOCKADDR_STORAGE *ss) {
    const GUID wsaid_connectex = WSAID_CONNECTEX;
    DWORD result;
    aeSockState *sockstate;

    if ((sockstate = aeGetSockState(iocpState, fd)) == NULL) {
        errno = WSAEINVAL;
        return SOCKET_ERROR;
    }

    if (aeWinSocketAttach(fd) != 0) {
        return SOCKET_ERROR;
    }

    memset(&sockstate->ov_read, 0, sizeof(sockstate->ov_read));
    
    /* need to bind sock before connectex */
    switch (ss->ss_family) {
        case AF_INET:
        {
            SOCKADDR_IN addr;
            memset(&addr, 0, sizeof(SOCKADDR_IN));
            addr.sin_family = ss->ss_family;
            addr.sin_addr.S_un.S_addr = INADDR_ANY;
            addr.sin_port = 0;
            result = bind(fd, (SOCKADDR*)&addr, sizeof(addr));

            result = FDAPI_ConnectEx(fd, (SOCKADDR*)ss, sizeof(SOCKADDR_IN), NULL, 0, NULL, &sockstate->ov_read);
            break;
        }
        case AF_INET6:
        {
            SOCKADDR_IN6 addr;
            memset(&addr, 0, sizeof(SOCKADDR_IN6));
            addr.sin6_family = ss->ss_family;
            memset(&(addr.sin6_addr.u.Byte), 0, 16);
            addr.sin6_port = 0;
            result = bind(fd, (SOCKADDR*)&addr, sizeof(addr));

            result = FDAPI_ConnectEx(fd, (SOCKADDR*)ss, sizeof(SOCKADDR_IN6), NULL, 0, NULL, &sockstate->ov_read);
            break;
        }
        default:
        {
            DebugBreak();
        }
    }

    if (result != TRUE) {
        result = WSAGetLastError();
        if (result == ERROR_IO_PENDING) {
            errno = WSA_IO_PENDING;
            sockstate->masks |= CONNECT_PENDING;
        } else {
            errno = result;
            return SOCKET_ERROR;
        }
    }
    return 0;
}

int aeWinSocketConnectBind(int fd, const SOCKADDR_STORAGE *ss, const char* source_addr) {
350
    const GUID wsaid_connectex = WSAID_CONNECTEX;
351
    DWORD result;
352 353 354 355 356 357 358 359 360 361 362 363
    aeSockState *sockstate;

    if ((sockstate = aeGetSockState(iocpState, fd)) == NULL) {
        errno = WSAEINVAL;
        return SOCKET_ERROR;
    }

    if (aeWinSocketAttach(fd) != 0) {
        return SOCKET_ERROR;
    }

    memset(&sockstate->ov_read, 0, sizeof(sockstate->ov_read));
364

365
    /* need to bind sock before connectex */
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    switch (ss->ss_family) {
        case AF_INET:
        {
            SOCKADDR_IN addr;
            memset(&addr, 0, sizeof(SOCKADDR_IN));
            addr.sin_family = ss->ss_family;
            addr.sin_addr.S_un.S_addr = INADDR_ANY;
            addr.sin_port = 0;
            result = bind(fd, (SOCKADDR*)&addr, sizeof(addr));
            break;
        }
        case AF_INET6:
        {
            SOCKADDR_IN6 addr;
            memset(&addr, 0, sizeof(SOCKADDR_IN6));
            addr.sin6_family = ss->ss_family;
            memset(&(addr.sin6_addr.u.Byte), 0, 16);
            addr.sin6_port = 0;
            result = bind(fd, (SOCKADDR*)&addr, sizeof(addr));
            break;
        }
        default:
        {
                   DebugBreak();
        }
    }
392

393
    result = FDAPI_ConnectEx(fd, (const LPSOCKADDR)ss, StorageSize(ss), NULL, 0, NULL, &sockstate->ov_read);
394 395 396 397 398 399 400 401 402 403 404 405 406
    if (result != TRUE) {
        result = WSAGetLastError();
        if (result == ERROR_IO_PENDING) {
            errno = WSA_IO_PENDING;
            sockstate->masks |= CONNECT_PENDING;
        } else {
            errno = result;
            return SOCKET_ERROR;
        }
    }
    return 0;
}

H
Henry Rawas 已提交
407 408 409 410 411 412 413 414 415 416 417
/* for each asynch socket, need to associate completion port */
int aeWinSocketAttach(int fd) {
    DWORD yes = 1;
    aeSockState *sockstate;

    if ((sockstate = aeGetSockState(iocpState, fd)) == NULL) {
        errno = WSAEINVAL;
        return -1;
    }

    /* Set the socket to nonblocking mode */
418
    if (ioctlsocket(fd, FIONBIO, &yes) == SOCKET_ERROR) {
H
Henry Rawas 已提交
419 420 421 422 423
        errno = WSAGetLastError();
        return -1;
    }

    /* Make the socket non-inheritable */
424
    if (!SetFDInformation(fd, HANDLE_FLAG_INHERIT, 0)) {
H
Henry Rawas 已提交
425 426 427 428 429
        errno = WSAGetLastError();
        return -1;
    }

    /* Associate it with the I/O completion port. */
430 431 432 433 434
    /* Use FD as completion key. */
    if (FDAPI_CreateIoCompletionPortOnFD(fd,
                                         iocph,
                                         (ULONG_PTR)fd,
                                         0) == NULL) {
H
Henry Rawas 已提交
435 436 437 438 439 440 441 442 443
        errno = WSAGetLastError();
        return -1;
    }
    sockstate->masks = SOCKET_ATTACHED;
    sockstate->wreqs = 0;

    return 0;
}

444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
void aeShutdown(int fd) {
    char rbuf[100];
    struct timeval timenow;
    long long waitmsecs = 50;      /* wait up to 50 millisecs */
    long long endms;
    long long nowms;

    /* wait for last item to complete up to tosecs seconds*/
    gettimeofday(&timenow, NULL);
    endms = ((long long)timenow.tv_sec * 1000) +
                    ((long long)timenow.tv_usec / 1000) + waitmsecs;

    if (shutdown(fd, SD_SEND) != SOCKET_ERROR) {
        /* read data until no more or error to ensure shutdown completed */
        while (1) {
459
            int rc = read(fd, rbuf, 100);
460 461 462 463 464 465 466 467 468 469 470 471 472
            if (rc == 0 || rc == SOCKET_ERROR)
                break;
            else {
                gettimeofday(&timenow, NULL);
                nowms = ((long long)timenow.tv_sec * 1000) +
                            ((long long)timenow.tv_usec / 1000);
                if (nowms > endms)
                    break;
            }
        }
    }
}

H
Henry Rawas 已提交
473
/* when closing socket, need to unassociate completion port */
474
int aeWinCloseSocket(int fd) {
H
Henry Rawas 已提交
475
    aeSockState *sockstate;
J
Jonathan Pickett 已提交
476
    BOOL closed = FALSE;
H
Henry Rawas 已提交
477 478

    if ((sockstate = aeGetSockState(iocpState, fd)) == NULL) {
479
        close(fd);
480
        return 0;
H
Henry Rawas 已提交
481 482
    }

483
    aeShutdown(fd);
H
Henry Rawas 已提交
484
    sockstate->masks &= ~(SOCKET_ATTACHED | AE_WRITABLE | AE_READABLE);
485 486 487

    if (sockstate->wreqs == 0 &&
        (sockstate->masks & (READ_QUEUED | CONNECT_PENDING | SOCKET_ATTACHED)) == 0) {
488
        close(fd);
J
Jonathan Pickett 已提交
489
        closed = TRUE;
490 491 492
    } else {
        sockstate->masks |= CLOSE_PENDING;
    }
H
Henry Rawas 已提交
493
    aeDelSockState(iocpState, sockstate);
494

H
Henry Rawas 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508
    return 0;
}

void aeWinInit(void *state, HANDLE iocp, fnGetSockState *getSockState,
                                        fnDelSockState *delSockState) {
    iocpState = state;
    iocph = iocp;
    aeGetSockState = getSockState;
    aeDelSockState = delSockState;
}

void aeWinCleanup() {
    iocpState = NULL;
}