1 /*
   2  * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Sun designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Sun in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  22  * CA 95054 USA or visit www.sun.com if you need additional information or
  23  * have any questions.
  24  */
  25 
  26 #include <windows.h>
  27 #include <winsock2.h>
  28 #include <ctype.h>
  29 #include <stdio.h>
  30 #include <stdlib.h>
  31 #include <malloc.h>
  32 #include <sys/types.h>
  33 #include <process.h>
  34 
  35 #include "java_net_InetAddress.h"
  36 #include "java_net_Inet4AddressImpl.h"
  37 #include "net_util.h"
  38 #include "icmp.h"
  39 
  40 
  41 /*
  42  * Returns true if hostname is in dotted IP address format. Note that this
  43  * function performs a syntax check only. For each octet it just checks that
  44  * the octet is at most 3 digits.
  45  */
  46 jboolean isDottedIPAddress(const char *hostname, unsigned int *addrp) {
  47     char *c = (char *)hostname;
  48     int octets = 0;
  49     unsigned int cur = 0;
  50     int digit_cnt = 0;
  51 
  52     while (*c) {
  53         if (*c == '.') {
  54             if (digit_cnt == 0) {
  55                 return JNI_FALSE;
  56             } else {
  57                 if (octets < 4) {
  58                     addrp[octets++] = cur;
  59                     cur = 0;
  60                     digit_cnt = 0;
  61                 } else {
  62                     return JNI_FALSE;
  63                 }
  64             }
  65             c++;
  66             continue;
  67         }
  68 
  69         if ((*c < '0') || (*c > '9')) {
  70             return JNI_FALSE;
  71         }
  72 
  73         digit_cnt++;
  74         if (digit_cnt > 3) {
  75             return JNI_FALSE;
  76         }
  77 
  78         /* don't check if current octet > 255 */
  79         cur = cur*10 + (*c - '0');
  80 
  81         /* Move onto next character and check for EOF */
  82         c++;
  83         if (*c == '\0') {
  84             if (octets < 4) {
  85                 addrp[octets++] = cur;
  86             } else {
  87                 return JNI_FALSE;
  88             }
  89         }
  90     }
  91 
  92     return (jboolean)(octets == 4);
  93 }
  94 
  95 /*
  96  * Inet4AddressImpl
  97  */
  98 
  99 /*
 100  * Class:     java_net_Inet4AddressImpl
 101  * Method:    getLocalHostName
 102  * Signature: ()Ljava/lang/String;
 103  */
 104 JNIEXPORT jstring JNICALL
 105 Java_java_net_Inet4AddressImpl_getLocalHostName (JNIEnv *env, jobject this) {
 106     char hostname[256];
 107 
 108     if (gethostname(hostname, sizeof hostname) == -1) {
 109         strcpy(hostname, "localhost");
 110     }
 111     return JNU_NewStringPlatform(env, hostname);
 112 }
 113 
 114 /*
 115  * Find an internet address for a given hostname.  Not this this
 116  * code only works for addresses of type INET. The translation
 117  * of %d.%d.%d.%d to an address (int) occurs in java now, so the
 118  * String "host" shouldn't be a %d.%d.%d.%d string. The only
 119  * exception should be when any of the %d are out of range and
 120  * we fallback to a lookup.
 121  *
 122  * Class:     java_net_Inet4AddressImpl
 123  * Method:    lookupAllHostAddr
 124  * Signature: (Ljava/lang/String;)[[B
 125  *
 126  * This is almost shared code
 127  */
 128 
 129 JNIEXPORT jobjectArray JNICALL
 130 Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
 131                                                 jstring host) {
 132     const char *hostname;
 133     struct hostent *hp;
 134     unsigned int addr[4];
 135 
 136     jobjectArray ret = NULL;
 137 
 138     init(env);
 139 
 140     if (IS_NULL(host)) {
 141         JNU_ThrowNullPointerException(env, "host argument");
 142         return NULL;
 143     }
 144     hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
 145     CHECK_NULL_RETURN(hostname, NULL);
 146 
 147     /*
 148      * The NT/2000 resolver tolerates a space in front of localhost. This
 149      * is not consistent with other implementations of gethostbyname.
 150      * In addition we must do a white space check on Solaris to avoid a
 151      * bug whereby 0.0.0.0 is returned if any host name has a white space.
 152      */
 153     if (isspace(hostname[0])) {
 154         JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", hostname);
 155         goto cleanupAndReturn;
 156     }
 157 
 158     /*
 159      * If the format is x.x.x.x then don't use gethostbyname as Windows
 160      * is unable to handle octets which are out of range.
 161      */
 162     if (isDottedIPAddress(hostname, &addr[0])) {
 163         unsigned int address;
 164         jobject iaObj;
 165 
 166         /*
 167          * Are any of the octets out of range?
 168          */
 169         if (addr[0] > 255 || addr[1] > 255 || addr[2] > 255 || addr[3] > 255) {
 170             JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", hostname);
 171             goto cleanupAndReturn;
 172         }
 173 
 174         /*
 175          * Return an byte array with the populated address.
 176          */
 177         address = (addr[3]<<24) & 0xff000000;
 178         address |= (addr[2]<<16) & 0xff0000;
 179         address |= (addr[1]<<8) & 0xff00;
 180         address |= addr[0];
 181 
 182         ret = (*env)->NewObjectArray(env, 1, ia_class, NULL);
 183 
 184         if (IS_NULL(ret)) {
 185             goto cleanupAndReturn;
 186         }
 187 
 188         iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
 189         if (IS_NULL(iaObj)) {
 190           ret = NULL;
 191           goto cleanupAndReturn;
 192         }
 193         (*env)->SetIntField(env, iaObj, ia_addressID,
 194                             ntohl(address));
 195         (*env)->SetObjectArrayElement(env, ret, 0, iaObj);
 196         JNU_ReleaseStringPlatformChars(env, host, hostname);
 197         return ret;
 198     }
 199 
 200     /*
 201      * Perform the lookup
 202      */
 203     if ((hp = gethostbyname((char*)hostname)) != NULL) {
 204         struct in_addr **addrp = (struct in_addr **) hp->h_addr_list;
 205         int len = sizeof(struct in_addr);
 206         int i = 0;
 207 
 208         while (*addrp != (struct in_addr *) 0) {
 209             i++;
 210             addrp++;
 211         }
 212 
 213         ret = (*env)->NewObjectArray(env, i, ia_class, NULL);
 214 
 215         if (IS_NULL(ret)) {
 216             goto cleanupAndReturn;
 217         }
 218 
 219         addrp = (struct in_addr **) hp->h_addr_list;
 220         i = 0;
 221         while (*addrp != (struct in_addr *) 0) {
 222           jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
 223           if (IS_NULL(iaObj)) {
 224             ret = NULL;
 225             goto cleanupAndReturn;
 226           }
 227           (*env)->SetIntField(env, iaObj, ia_addressID,
 228                               ntohl((*addrp)->s_addr));
 229           (*env)->SetObjectField(env, iaObj, ia_hostNameID, host);
 230           (*env)->SetObjectArrayElement(env, ret, i, iaObj);
 231           addrp++;
 232           i++;
 233         }
 234     } else {
 235         JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", hostname);
 236     }
 237 
 238 cleanupAndReturn:
 239     JNU_ReleaseStringPlatformChars(env, host, hostname);
 240     return ret;
 241 }
 242 
 243 /*
 244  * Class:     java_net_Inet4AddressImpl
 245  * Method:    getHostByAddr
 246  * Signature: (I)Ljava/lang/String;
 247  */
 248 JNIEXPORT jstring JNICALL
 249 Java_java_net_Inet4AddressImpl_getHostByAddr(JNIEnv *env, jobject this,
 250                                             jbyteArray addrArray) {
 251     struct hostent *hp;
 252     jbyte caddr[4];
 253     jint addr;
 254     (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
 255     addr = ((caddr[0]<<24) & 0xff000000);
 256     addr |= ((caddr[1] <<16) & 0xff0000);
 257     addr |= ((caddr[2] <<8) & 0xff00);
 258     addr |= (caddr[3] & 0xff);
 259     addr = htonl(addr);
 260 
 261     hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
 262     if (hp == NULL) {
 263         JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", 0);
 264         return NULL;
 265     }
 266     if (hp->h_name == NULL) { /* Deal with bug in Windows XP */
 267         JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", 0);
 268         return NULL;
 269     }
 270     return JNU_NewStringPlatform(env, hp->h_name);
 271 }
 272 
 273 
 274 /**
 275  * ping implementation.
 276  * Send a ICMP_ECHO_REQUEST packet every second until either the timeout
 277  * expires or a answer is received.
 278  * Returns true is an ECHO_REPLY is received, otherwise, false.
 279  */
 280 static jboolean
 281 ping4(JNIEnv *env, jint fd, struct sockaddr_in* him, jint timeout,
 282       struct sockaddr_in* netif, jint ttl) {
 283     jint size;
 284     jint n, len, hlen1, icmplen;
 285     char sendbuf[1500];
 286     char recvbuf[1500];
 287     struct icmp *icmp;
 288     struct ip *ip;
 289     WSAEVENT hEvent;
 290     struct sockaddr sa_recv;
 291     jint tmout2;
 292     u_short pid, seq;
 293     int read_rv = 0;
 294 
 295     /* Initialize the sequence number to a suitable random number and
 296        shift right one place to allow sufficient room for increamenting. */
 297     seq = ((unsigned short)rand()) >> 1;
 298 
 299     /* icmp_id is a 16 bit data type, therefore down cast the pid */
 300     pid = (u_short) _getpid();
 301     size = 60*1024;
 302     setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char *) &size, sizeof(size));
 303     /**
 304      * A TTL was specified, let's set the socket option.
 305      */
 306     if (ttl > 0) {
 307       setsockopt(fd, IPPROTO_IP, IP_TTL, (const char *) &ttl, sizeof(ttl));
 308     }
 309 
 310     /**
 311      * A network interface was specified, let's bind to it.
 312      */
 313     if (netif != NULL) {
 314       if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in)) < 0) {
 315         NET_ThrowNew(env, WSAGetLastError(), "Can't bind socket");
 316         closesocket(fd);
 317         return JNI_FALSE;
 318       }
 319     }
 320 
 321     /**
 322      * Let's make the socket non blocking
 323      */
 324     hEvent = WSACreateEvent();
 325     WSAEventSelect(fd, hEvent, FD_READ|FD_CONNECT|FD_CLOSE);
 326 
 327     /**
 328      * send 1 ICMP REQUEST every second until either we get a valid reply
 329      * or the timeout expired.
 330      */
 331     do {
 332       /**
 333        * construct the ICMP header
 334        */
 335       memset(sendbuf, 0, 1500);
 336       icmp = (struct icmp *) sendbuf;
 337       icmp->icmp_type = ICMP_ECHO;
 338       icmp->icmp_code = 0;
 339       icmp->icmp_id = htons(pid);
 340       icmp->icmp_seq = htons(seq);
 341       /**
 342        * checksum has to be set to zero before we can calculate the
 343        * real checksum!
 344        */
 345       icmp->icmp_cksum = 0;
 346       icmp->icmp_cksum = in_cksum((u_short *)icmp, 64);
 347       /**
 348        * Ping!
 349        */
 350       n = sendto(fd, sendbuf, 64, 0, (struct sockaddr *)him,
 351                  sizeof(struct sockaddr));
 352       if (n < 0 && WSAGetLastError() != WSAEWOULDBLOCK) {
 353         NET_ThrowNew(env, WSAGetLastError(), "Can't send ICMP packet");
 354         closesocket(fd);
 355         WSACloseEvent(hEvent);
 356         return JNI_FALSE;
 357       }
 358 
 359       /*
 360        * wait for 1 second at most
 361        */
 362       tmout2 = timeout > 1000 ? 1000 : timeout;
 363       do {
 364         tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2);
 365         if (tmout2 >= 0) {
 366           len = sizeof(sa_recv);
 367           n = recvfrom(fd, recvbuf, sizeof(recvbuf), 0, &sa_recv, &len);
 368           ip = (struct ip*) recvbuf;
 369           hlen1 = (ip->ip_hl) << 2;
 370           icmp = (struct icmp *) (recvbuf + hlen1);
 371           icmplen = n - hlen1;
 372           /**
 373            * Is that a proper ICMP reply?
 374            */
 375           if (icmplen >= 8 && icmp->icmp_type == ICMP_ECHOREPLY &&
 376               (ntohs(icmp->icmp_seq) == seq) && (ntohs(icmp->icmp_id) == pid)) {
 377             closesocket(fd);
 378             WSACloseEvent(hEvent);
 379             return JNI_TRUE;
 380           }
 381         }
 382       } while (tmout2 > 0);
 383       timeout -= 1000;
 384       seq++;
 385     } while (timeout > 0);
 386     closesocket(fd);
 387     WSACloseEvent(hEvent);
 388     return JNI_FALSE;
 389 }
 390 
 391 /*
 392  * Class:     java_net_Inet4AddressImpl
 393  * Method:    isReachable0
 394  * Signature: ([bI[bI)Z
 395  */
 396 JNIEXPORT jboolean JNICALL
 397 Java_java_net_Inet4AddressImpl_isReachable0(JNIEnv *env, jobject this,
 398                                            jbyteArray addrArray,
 399                                            jint timeout,
 400                                            jbyteArray ifArray,
 401                                            jint ttl) {
 402     jint addr;
 403     jbyte caddr[4];
 404     jint fd;
 405     struct sockaddr_in him;
 406     struct sockaddr_in* netif = NULL;
 407     struct sockaddr_in inf;
 408     int len = 0;
 409     WSAEVENT hEvent;
 410     int connect_rv = -1;
 411     int sz;
 412 
 413     /**
 414      * Convert IP address from byte array to integer
 415      */
 416     sz = (*env)->GetArrayLength(env, addrArray);
 417     if (sz != 4) {
 418       return JNI_FALSE;
 419     }
 420     memset((char *) &him, 0, sizeof(him));
 421     memset((char *) caddr, 0, sizeof(caddr));
 422     (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
 423     addr = ((caddr[0]<<24) & 0xff000000);
 424     addr |= ((caddr[1] <<16) & 0xff0000);
 425     addr |= ((caddr[2] <<8) & 0xff00);
 426     addr |= (caddr[3] & 0xff);
 427     addr = htonl(addr);
 428     /**
 429      * Socket address
 430      */
 431     him.sin_addr.s_addr = addr;
 432     him.sin_family = AF_INET;
 433     len = sizeof(him);
 434 
 435     /**
 436      * If a network interface was specified, let's convert its address
 437      * as well.
 438      */
 439     if (!(IS_NULL(ifArray))) {
 440       memset((char *) caddr, 0, sizeof(caddr));
 441       (*env)->GetByteArrayRegion(env, ifArray, 0, 4, caddr);
 442       addr = ((caddr[0]<<24) & 0xff000000);
 443       addr |= ((caddr[1] <<16) & 0xff0000);
 444       addr |= ((caddr[2] <<8) & 0xff00);
 445       addr |= (caddr[3] & 0xff);
 446       addr = htonl(addr);
 447       inf.sin_addr.s_addr = addr;
 448       inf.sin_family = AF_INET;
 449       inf.sin_port = 0;
 450       netif = &inf;
 451     }
 452 
 453 #if 0
 454     /*
 455      * Windows implementation of ICMP & RAW sockets is too unreliable for now.
 456      * Therefore it's best not to try it at all and rely only on TCP
 457      * We may revisit and enable this code in the future.
 458      */
 459 
 460     /*
 461      * Let's try to create a RAW socket to send ICMP packets
 462      * This usually requires "root" privileges, so it's likely to fail.
 463      */
 464     fd = NET_Socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
 465     if (fd != -1) {
 466       /*
 467        * It didn't fail, so we can use ICMP_ECHO requests.
 468        */
 469         return ping4(env, fd, &him, timeout, netif, ttl);
 470     }
 471 #endif
 472 
 473     /*
 474      * Can't create a raw socket, so let's try a TCP socket
 475      */
 476     fd = NET_Socket(AF_INET, SOCK_STREAM, 0);
 477     if (fd == JVM_IO_ERR) {
 478         /* note: if you run out of fds, you may not be able to load
 479          * the exception class, and get a NoClassDefFoundError
 480          * instead.
 481          */
 482         NET_ThrowNew(env, WSAGetLastError(), "Can't create socket");
 483         return JNI_FALSE;
 484     }
 485     if (ttl > 0) {
 486       setsockopt(fd, IPPROTO_IP, IP_TTL, (const char *)&ttl, sizeof(ttl));
 487     }
 488     /*
 489      * A network interface was specified, so let's bind to it.
 490      */
 491     if (netif != NULL) {
 492       if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in)) < 0) {
 493         NET_ThrowNew(env, WSAGetLastError(), "Can't bind socket");
 494         closesocket(fd);
 495         return JNI_FALSE;
 496       }
 497     }
 498 
 499     /*
 500      * Make the socket non blocking so we can use select/poll.
 501      */
 502     hEvent = WSACreateEvent();
 503     WSAEventSelect(fd, hEvent, FD_READ|FD_CONNECT|FD_CLOSE);
 504 
 505     /* no need to use NET_Connect as non-blocking */
 506     him.sin_port = htons(7);    /* Echo */
 507     connect_rv = connect(fd, (struct sockaddr *)&him, len);
 508 
 509     /**
 510      * connection established or refused immediately, either way it means
 511      * we were able to reach the host!
 512      */
 513     if (connect_rv == 0 || WSAGetLastError() == WSAECONNREFUSED) {
 514         WSACloseEvent(hEvent);
 515         closesocket(fd);
 516         return JNI_TRUE;
 517     } else {
 518         int optlen;
 519 
 520         switch (WSAGetLastError()) {
 521         case WSAEHOSTUNREACH:   /* Host Unreachable */
 522         case WSAENETUNREACH:    /* Network Unreachable */
 523         case WSAENETDOWN:       /* Network is down */
 524         case WSAEPFNOSUPPORT:   /* Protocol Family unsupported */
 525           WSACloseEvent(hEvent);
 526           closesocket(fd);
 527           return JNI_FALSE;
 528         }
 529 
 530         if (WSAGetLastError() != WSAEWOULDBLOCK) {
 531             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
 532                                          "connect failed");
 533             WSACloseEvent(hEvent);
 534             closesocket(fd);
 535             return JNI_FALSE;
 536         }
 537 
 538         timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
 539 
 540         /* has connection been established */
 541 
 542         if (timeout >= 0) {
 543           optlen = sizeof(connect_rv);
 544           if (JVM_GetSockOpt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
 545                              &optlen) <0) {
 546             connect_rv = WSAGetLastError();
 547           }
 548 
 549           if (connect_rv == 0 || connect_rv == WSAECONNREFUSED) {
 550             WSACloseEvent(hEvent);
 551             closesocket(fd);
 552             return JNI_TRUE;
 553           }
 554         }
 555     }
 556     WSACloseEvent(hEvent);
 557     closesocket(fd);
 558     return JNI_FALSE;
 559 }