socket_md.c 12.8 KB
Newer Older
D
duke 已提交
1
/*
X
xdono 已提交
2
 * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code 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 General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */
#include <windows.h>
#include <winsock2.h>

#include "sysSocket.h"
#include "socketTransport.h"

typedef jboolean bool_t;

/*
 * Table of Windows Sockets errors, the specific exception we
 * throw for the error, and the error text.
 *
 * Note that this table excludes OS dependent errors.
 */
static struct {
    int errCode;
    const char *errString;
} const winsock_errors[] = {
    { WSAEPROVIDERFAILEDINIT,   "Provider initialization failed (check %SystemRoot%)" },
    { WSAEACCES,                "Permission denied" },
    { WSAEADDRINUSE,            "Address already in use" },
    { WSAEADDRNOTAVAIL,         "Cannot assign requested address" },
    { WSAEAFNOSUPPORT,          "Address family not supported by protocol family" },
    { WSAEALREADY,              "Operation already in progress" },
    { WSAECONNABORTED,          "Software caused connection abort" },
    { WSAECONNREFUSED,          "Connection refused" },
    { WSAECONNRESET,            "Connection reset by peer" },
    { WSAEDESTADDRREQ,          "Destination address required" },
    { WSAEFAULT,                "Bad address" },
    { WSAEHOSTDOWN,             "Host is down" },
    { WSAEHOSTUNREACH,          "No route to host" },
    { WSAEINPROGRESS,           "Operation now in progress" },
    { WSAEINTR,                 "Interrupted function call" },
    { WSAEINVAL,                "Invalid argument" },
    { WSAEISCONN,               "Socket is already connected" },
    { WSAEMFILE,                "Too many open files" },
    { WSAEMSGSIZE,              "The message is larger than the maximum supported by the underlying transport" },
    { WSAENETDOWN,              "Network is down" },
    { WSAENETRESET,             "Network dropped connection on reset" },
    { WSAENETUNREACH,           "Network is unreachable" },
    { WSAENOBUFS,               "No buffer space available (maximum connections reached?)" },
    { WSAENOPROTOOPT,           "Bad protocol option" },
    { WSAENOTCONN,              "Socket is not connected" },
    { WSAENOTSOCK,              "Socket operation on nonsocket" },
    { WSAEOPNOTSUPP,            "Operation not supported" },
    { WSAEPFNOSUPPORT,          "Protocol family not supported" },
    { WSAEPROCLIM,              "Too many processes" },
    { WSAEPROTONOSUPPORT,       "Protocol not supported" },
    { WSAEPROTOTYPE,            "Protocol wrong type for socket" },
    { WSAESHUTDOWN,             "Cannot send after socket shutdown" },
    { WSAESOCKTNOSUPPORT,       "Socket type not supported" },
    { WSAETIMEDOUT,             "Connection timed out" },
    { WSATYPE_NOT_FOUND,        "Class type not found" },
    { WSAEWOULDBLOCK,           "Resource temporarily unavailable" },
    { WSAHOST_NOT_FOUND,        "Host not found" },
    { WSA_NOT_ENOUGH_MEMORY,    "Insufficient memory available" },
    { WSANOTINITIALISED,        "Successful WSAStartup not yet performed" },
    { WSANO_DATA,               "Valid name, no data record of requested type" },
    { WSANO_RECOVERY,           "This is a nonrecoverable error" },
    { WSASYSNOTREADY,           "Network subsystem is unavailable" },
    { WSATRY_AGAIN,             "Nonauthoritative host not found" },
    { WSAVERNOTSUPPORTED,       "Winsock.dll version out of range" },
    { WSAEDISCON,               "Graceful shutdown in progress" },
    { WSA_OPERATION_ABORTED,    "Overlapped operation aborted" },
};


/*
 * Initialize Windows Sockets API support
 */
BOOL WINAPI
DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved)
{
    WSADATA wsadata;

    switch (reason) {
        case DLL_PROCESS_ATTACH:
            if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0) {
                return FALSE;
            }
            break;

        case DLL_PROCESS_DETACH:
            WSACleanup();
            break;

        default:
            break;
    }
    return TRUE;
}

/*
 * If we get a nonnull function pointer it might still be the case
 * that some other thread is in the process of initializing the socket
 * function pointer table, but our pointer should still be good.
 */
int
123 124
dbgsysListen(int fd, int backlog) {
    return listen(fd, backlog);
D
duke 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
}

int
dbgsysConnect(int fd, struct sockaddr *name, int namelen) {
    int rv = connect(fd, name, namelen);
    if (rv == SOCKET_ERROR) {
        if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK) {
            return DBG_EINPROGRESS;
        }
    }
    return rv;
}

int dbgsysFinishConnect(int fd, long timeout) {
    int rv;
    struct timeval t;
    fd_set wr, ex;

    t.tv_sec = timeout / 1000;
    t.tv_usec = (timeout % 1000) * 1000;

    FD_ZERO(&wr);
    FD_ZERO(&ex);
    FD_SET((unsigned int)fd, &wr);
    FD_SET((unsigned int)fd, &ex);

    rv = select(fd+1, 0, &wr, &ex, &t);
    if (rv == 0) {
        return SYS_ERR;     /* timeout */
    }

    /*
     * Check if there was an error - this is preferable to check if
     * the socket is writable because some versions of Windows don't
     * report a connected socket as being writable.
     */
    if (!FD_ISSET(fd, &ex)) {
        return SYS_OK;
    }

    /*
     * Unable to establish connection - to get the reason we must
     * call getsockopt.
     */
    return SYS_ERR;
}


int
dbgsysAccept(int fd, struct sockaddr *name, int *namelen) {
175
    return (int)accept(fd, name, namelen);
D
duke 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
}

int
dbgsysRecvFrom(int fd, char *buf, int nBytes,
                  int flags, struct sockaddr *from, int *fromlen) {
    return recvfrom(fd, buf, nBytes, flags, from, fromlen);
}

int
dbgsysSendTo(int fd, char *buf, int len,
                int flags, struct sockaddr *to, int tolen) {
    return sendto(fd, buf, len, flags, to, tolen);
}

int
dbgsysRecv(int fd, char *buf, int nBytes, int flags) {
    return recv(fd, buf, nBytes, flags);
}

int
dbgsysSend(int fd, char *buf, int nBytes, int flags) {
    return send(fd, buf, nBytes, flags);
}

struct hostent *
dbgsysGetHostByName(char *hostname) {
    return gethostbyname(hostname);
}

unsigned short
dbgsysHostToNetworkShort(unsigned short hostshort) {
    return htons(hostshort);
}

int
dbgsysSocket(int domain, int type, int protocol) {
212
  int fd = (int)socket(domain, type, protocol);
D
duke 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
  if (fd != SOCKET_ERROR) {
      SetHandleInformation((HANDLE)(UINT_PTR)fd, HANDLE_FLAG_INHERIT, FALSE);
  }
  return fd;
}

int
dbgsysSocketClose(int fd) {
    struct linger l;
    int len = sizeof(l);

    if (getsockopt(fd, SOL_SOCKET, SO_LINGER, (char *)&l, &len) == 0) {
        if (l.l_onoff == 0) {
            WSASendDisconnect(fd, NULL);
        }
    }
    return closesocket(fd);
}

/* Additions to original follow */

int
dbgsysBind(int fd, struct sockaddr *name, int namelen) {
    return bind(fd, name, namelen);
}


240
uint32_t
D
duke 已提交
241
dbgsysInetAddr(const char* cp) {
242
    return (uint32_t)inet_addr(cp);
D
duke 已提交
243 244
}

245 246 247
uint32_t
dbgsysHostToNetworkLong(uint32_t hostlong) {
    return (uint32_t)htonl((u_long)hostlong);
D
duke 已提交
248 249 250 251 252 253 254 255 256 257 258 259
}

unsigned short
dbgsysNetworkToHostShort(unsigned short netshort) {
    return ntohs(netshort);
}

int
dbgsysGetSocketName(int fd, struct sockaddr *name, int *namelen) {
    return getsockname(fd, name, namelen);
}

260 261 262
uint32_t
dbgsysNetworkToHostLong(uint32_t netlong) {
    return (uint32_t)ntohl((u_long)netlong);
D
duke 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 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 392 393 394 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 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
}

/*
 * Below Adapted from PlainSocketImpl.c, win32 version 1.18. Changed exception
 * throws to returns of SYS_ERR; we should improve the error codes
 * eventually. Changed java objects to values the debugger back end can
 * more easily deal with.
 */

int
dbgsysSetSocketOption(int fd, jint cmd, jboolean on, jvalue value)
{
    if (cmd == TCP_NODELAY) {
        struct protoent *proto = getprotobyname("TCP");
        int tcp_level = (proto == 0 ? IPPROTO_TCP: proto->p_proto);
        long onl = (long)on;

        if (setsockopt(fd, tcp_level, TCP_NODELAY,
                       (char *)&onl, sizeof(long)) < 0) {
                return SYS_ERR;
        }
    } else if (cmd == SO_LINGER) {
        struct linger arg;
        arg.l_onoff = on;

        if(on) {
            arg.l_linger = (unsigned short)value.i;
            if(setsockopt(fd, SOL_SOCKET, SO_LINGER,
                          (char*)&arg, sizeof(arg)) < 0) {
                return SYS_ERR;
            }
        } else {
            if (setsockopt(fd, SOL_SOCKET, SO_LINGER,
                           (char*)&arg, sizeof(arg)) < 0) {
                return SYS_ERR;
            }
        }
    } else if (cmd == SO_SNDBUF) {
        jint buflen = value.i;
        if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF,
                       (char *)&buflen, sizeof(buflen)) < 0) {
            return SYS_ERR;
        }
    } else if (cmd == SO_REUSEADDR) {
        /*
         * On Windows the SO_REUSEADDR socket option doesn't implement
         * BSD semantics. Specifically, the socket option allows multiple
         * processes to bind to the same address/port rather than allowing
         * a process to bind with a previous connection in the TIME_WAIT
         * state. Hence on Windows we never enable this option for TCP
         * option.
         */
        int sotype, arglen=sizeof(sotype);
        if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen) == SOCKET_ERROR) {
            return SYS_ERR;
        }
        if (sotype != SOCK_STREAM) {
            int oni = (int)on;
            if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
                       (char *)&oni, sizeof(oni)) == SOCKET_ERROR) {
                return SYS_ERR;
            }
        }
    } else {
        return SYS_ERR;
    }
    return SYS_OK;
}

int dbgsysConfigureBlocking(int fd, jboolean blocking) {
    u_long argp;
    int result = 0;

    if (blocking == JNI_FALSE) {
        argp = 1;
    } else {
        argp = 0;
    }
    result = ioctlsocket(fd, FIONBIO, &argp);
    if (result == SOCKET_ERROR) {
        return SYS_ERR;
    } else {
        return SYS_OK;
    }
}

int
dbgsysPoll(int fd, jboolean rd, jboolean wr, long timeout) {
    int rv;
    struct timeval t;
    fd_set rd_tbl, wr_tbl;

    t.tv_sec = timeout / 1000;
    t.tv_usec = (timeout % 1000) * 1000;

    FD_ZERO(&rd_tbl);
    if (rd) {
        FD_SET((unsigned int)fd, &rd_tbl);
    }

    FD_ZERO(&wr_tbl);
    if (wr) {
        FD_SET((unsigned int)fd, &wr_tbl);
    }

    rv = select(fd+1, &rd_tbl, &wr_tbl, 0, &t);
    if (rv >= 0) {
        rv = 0;
        if (FD_ISSET(fd, &rd_tbl)) {
            rv |= DBG_POLLIN;
        }
        if (FD_ISSET(fd, &wr_tbl)) {
            rv |= DBG_POLLOUT;
        }
    }
    return rv;
}

int
dbgsysGetLastIOError(char *buf, jint size) {
    int table_size = sizeof(winsock_errors) /
                     sizeof(winsock_errors[0]);
    int i;
    int error = WSAGetLastError();

    /*
     * Check table for known winsock errors
     */
    i=0;
    while (i < table_size) {
        if (error == winsock_errors[i].errCode) {
            break;
        }
        i++;
    }

    if (i < table_size) {
        strcpy(buf, winsock_errors[i].errString);
    } else {
        sprintf(buf, "winsock error %d", error);
    }
    return 0;
}


int
dbgsysTlsAlloc() {
    return TlsAlloc();
}

void
dbgsysTlsFree(int index) {
    TlsFree(index);
}

void
dbgsysTlsPut(int index, void *value) {
    TlsSetValue(index, value);
}

void *
dbgsysTlsGet(int index) {
    return TlsGetValue(index);
}

#define FT2INT64(ft) \
        ((long)(ft).dwHighDateTime << 32 | (long)(ft).dwLowDateTime)

long
dbgsysCurrentTimeMillis() {
    static long fileTime_1_1_70 = 0;    /* midnight 1/1/70 */
    SYSTEMTIME st0;
    FILETIME   ft0;

    /* initialize on first usage */
    if (fileTime_1_1_70 == 0) {
        memset(&st0, 0, sizeof(st0));
        st0.wYear  = 1970;
        st0.wMonth = 1;
        st0.wDay   = 1;
        SystemTimeToFileTime(&st0, &ft0);
        fileTime_1_1_70 = FT2INT64(ft0);
    }

    GetSystemTime(&st0);
    SystemTimeToFileTime(&st0, &ft0);

    return (FT2INT64(ft0) - fileTime_1_1_70) / 10000;
}