1 /*
   2  * Copyright (c) 2001, 2012, Oracle and/or its affiliates. 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include "jni.h"
  27 #include "jni_util.h"
  28 #include "jvm.h"
  29 #include "jlong.h"
  30 #include <io.h>
  31 #include "sun_nio_ch_DatagramChannelImpl.h"
  32 #include "nio.h"
  33 #include "nio_util.h"
  34 #include "net_util.h"
  35 #include <winsock2.h>
  36 
  37 static jfieldID dci_senderID;   /* sender in sun.nio.ch.DatagramChannelImpl */
  38 static jfieldID dci_senderAddrID; /* sender InetAddress in sun.nio.ch.DatagramChannelImpl */
  39 static jfieldID dci_senderPortID; /* sender port in sun.nio.ch.DatagramChannelImpl */
  40 static jclass isa_class;        /* java.net.InetSocketAddress */
  41 static jmethodID isa_ctorID;    /* java.net.InetSocketAddress(InetAddress, int) */
  42 
  43 
  44 JNIEXPORT void JNICALL
  45 Java_sun_nio_ch_DatagramChannelImpl_initIDs(JNIEnv *env, jclass clazz)
  46 {
  47     clazz = (*env)->FindClass(env, "java/net/InetSocketAddress");
  48     CHECK_NULL(clazz);
  49     isa_class = (*env)->NewGlobalRef(env, clazz);
  50     if (isa_class == NULL) {
  51         JNU_ThrowOutOfMemoryError(env, NULL);
  52         return;
  53     }
  54     isa_ctorID = (*env)->GetMethodID(env, clazz, "<init>",
  55                                      "(Ljava/net/InetAddress;I)V");
  56     CHECK_NULL(isa_ctorID);
  57 
  58     clazz = (*env)->FindClass(env, "sun/nio/ch/DatagramChannelImpl");
  59     CHECK_NULL(clazz);
  60     dci_senderID = (*env)->GetFieldID(env, clazz, "sender",
  61                                       "Ljava/net/SocketAddress;");
  62     CHECK_NULL(dci_senderID);
  63     dci_senderAddrID = (*env)->GetFieldID(env, clazz,
  64                                           "cachedSenderInetAddress",
  65                                           "Ljava/net/InetAddress;");
  66     CHECK_NULL(dci_senderAddrID);
  67     dci_senderPortID = (*env)->GetFieldID(env, clazz,
  68                                           "cachedSenderPort", "I");
  69     CHECK_NULL(dci_senderPortID);
  70 }
  71 
  72 /*
  73  * This function "purges" all outstanding ICMP port unreachable packets
  74  * outstanding on a socket and returns JNI_TRUE if any ICMP messages
  75  * have been purged. The rational for purging is to emulate normal BSD
  76  * behaviour whereby receiving a "connection reset" status resets the
  77  * socket.
  78  */
  79 jboolean purgeOutstandingICMP(JNIEnv *env, jclass clazz, jint fd)
  80 {
  81     jboolean got_icmp = JNI_FALSE;
  82     char buf[1];
  83     fd_set tbl;
  84     struct timeval t = { 0, 0 };
  85     SOCKETADDRESS sa;
  86     int addrlen = sizeof(sa);
  87 
  88     /*
  89      * Peek at the queue to see if there is an ICMP port unreachable. If there
  90      * is then receive it.
  91      */
  92     FD_ZERO(&tbl);
  93     FD_SET((u_int)fd, &tbl);
  94     while(1) {
  95         if (select(/*ignored*/fd+1, &tbl, 0, 0, &t) <= 0) {
  96             break;
  97         }
  98         if (recvfrom(fd, buf, 1, MSG_PEEK,
  99                      &sa.sa, &addrlen) != SOCKET_ERROR) {
 100             break;
 101         }
 102         if (WSAGetLastError() != WSAECONNRESET) {
 103             /* some other error - we don't care here */
 104             break;
 105         }
 106 
 107         recvfrom(fd, buf, 1, 0, &sa.sa, &addrlen);
 108         got_icmp = JNI_TRUE;
 109     }
 110 
 111     return got_icmp;
 112 }
 113 
 114 JNIEXPORT void JNICALL
 115 Java_sun_nio_ch_DatagramChannelImpl_disconnect0(JNIEnv *env, jobject this,
 116                                                 jobject fdo, jboolean isIPv6)
 117 {
 118     jint fd = fdval(env, fdo);
 119     int rv = 0;
 120     SOCKETADDRESS sa;
 121     int sa_len = sizeof(sa);
 122 
 123     memset(&sa, 0, sa_len);
 124 
 125     rv = connect((SOCKET)fd, &sa.sa, sa_len);
 126     if (rv == SOCKET_ERROR) {
 127         handleSocketError(env, WSAGetLastError());
 128     } else {
 129         /* Disable WSAECONNRESET errors as socket is no longer connected */
 130         BOOL enable = FALSE;
 131         DWORD bytesReturned = 0;
 132         WSAIoctl((SOCKET)fd, SIO_UDP_CONNRESET, &enable, sizeof(enable),
 133                  NULL, 0, &bytesReturned, NULL, NULL);
 134     }
 135 }
 136 
 137 JNIEXPORT jint JNICALL
 138 Java_sun_nio_ch_DatagramChannelImpl_receive0(JNIEnv *env, jobject this,
 139                                             jobject fdo, jlong address,
 140                                             jint len, jboolean connected)
 141 {
 142     jint fd = fdval(env, fdo);
 143     void *buf = (void *)jlong_to_ptr(address);
 144     SOCKETADDRESS sa;
 145     int sa_len = sizeof(sa);
 146     BOOL retry = FALSE;
 147     jint n;
 148     jobject senderAddr;
 149 
 150     do {
 151         retry = FALSE;
 152         n = recvfrom((SOCKET)fd,
 153                      (char *)buf,
 154                      len,
 155                      0,
 156                      &sa.sa,
 157                      &sa_len);
 158 
 159         if (n == SOCKET_ERROR) {
 160             int theErr = (jint)WSAGetLastError();
 161             if (theErr == WSAEMSGSIZE) {
 162                 /* Spec says the rest of the data will be discarded... */
 163                 n = len;
 164             } else if (theErr == WSAECONNRESET) {
 165                 purgeOutstandingICMP(env, this, fd);
 166                 if (connected == JNI_FALSE) {
 167                     retry = TRUE;
 168                 } else {
 169                     JNU_ThrowByName(env, JNU_JAVANETPKG "PortUnreachableException", 0);
 170                     return IOS_THROWN;
 171                 }
 172             } else if (theErr == WSAEWOULDBLOCK) {
 173                 return IOS_UNAVAILABLE;
 174             } else return handleSocketError(env, theErr);
 175         } else if (n > 0) {
 176           JVM_callNetworkReadBytes(env, n);
 177         }
 178     } while (retry);
 179 
 180     /*
 181      * If the source address and port match the cached address
 182      * and port in DatagramChannelImpl then we don't need to
 183      * create InetAddress and InetSocketAddress objects.
 184      */
 185     senderAddr = (*env)->GetObjectField(env, this, dci_senderAddrID);
 186     if (senderAddr != NULL) {
 187         if (!NET_SockaddrEqualsInetAddress(env, &sa, senderAddr)) {
 188             senderAddr = NULL;
 189         } else {
 190             jint port = (*env)->GetIntField(env, this, dci_senderPortID);
 191             if (port != NET_GetPortFromSockaddr(&sa)) {
 192                 senderAddr = NULL;
 193             }
 194         }
 195     }
 196     if (senderAddr == NULL) {
 197         jobject isa = NULL;
 198         int port;
 199         jobject ia = NET_SockaddrToInetAddress(env, &sa, &port);
 200         if (ia != NULL) {
 201             isa = (*env)->NewObject(env, isa_class, isa_ctorID, ia, port);
 202         }
 203         CHECK_NULL_RETURN(isa, IOS_THROWN);
 204 
 205         // update cachedSenderInetAddress/cachedSenderPort
 206         (*env)->SetObjectField(env, this, dci_senderAddrID, ia);
 207         (*env)->SetIntField(env, this, dci_senderPortID,
 208                             NET_GetPortFromSockaddr(&sa));
 209         (*env)->SetObjectField(env, this, dci_senderID, isa);
 210     }
 211     return n;
 212 }
 213 
 214 JNIEXPORT jint JNICALL
 215 Java_sun_nio_ch_DatagramChannelImpl_send0(JNIEnv *env, jobject this,
 216                                           jboolean preferIPv6, jobject fdo,
 217                                           jlong address, jint len,
 218                                           jobject destAddress, jint destPort)
 219 {
 220     jint fd = fdval(env, fdo);
 221     void *buf = (void *)jlong_to_ptr(address);
 222     SOCKETADDRESS sa;
 223     int sa_len = 0;
 224     jint rv = 0;
 225 
 226     if (NET_InetAddressToSockaddr(env, destAddress, destPort, &sa,
 227                                   &sa_len, preferIPv6) != 0) {
 228       return IOS_THROWN;
 229     }
 230 
 231     rv = sendto((SOCKET)fd, buf, len, 0, &sa.sa, sa_len);
 232     if (rv == SOCKET_ERROR) {
 233         int theErr = (jint)WSAGetLastError();
 234         if (theErr == WSAEWOULDBLOCK) {
 235             return IOS_UNAVAILABLE;
 236         }
 237         return handleSocketError(env, (jint)WSAGetLastError());
 238     }
 239 
 240     if (rv > 0) {
 241       JVM_callFileWriteBytes(env, rv);
 242     }
 243 
 244     return rv;
 245 }