1 /*
   2  * Copyright (c) 1997, 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 <errno.h>
  27 #include <string.h>
  28 #include <sys/types.h>
  29 #include <sys/socket.h>
  30 #if defined(__linux__) && !defined(USE_SELECT)
  31 #include <sys/poll.h>
  32 #endif
  33 #include <netinet/tcp.h>        /* Defines TCP_NODELAY, needed for 2.6 */
  34 #include <netinet/in.h>
  35 #ifdef __linux__
  36 #include <netinet/ip.h>
  37 #endif
  38 #include <netdb.h>
  39 #include <stdlib.h>
  40 
  41 #ifdef __solaris__
  42 #include <fcntl.h>
  43 #endif
  44 #ifdef __linux__
  45 #include <unistd.h>
  46 #include <sys/sysctl.h>
  47 #endif
  48 
  49 #include "jvm.h"
  50 #include "jni_util.h"
  51 #include "net_util.h"
  52 
  53 #include "java_net_SocketOptions.h"
  54 #include "java_net_PlainSocketImpl.h"
  55 
  56 /************************************************************************
  57  * PlainSocketImpl
  58  */
  59 
  60 static jfieldID IO_fd_fdID;
  61 
  62 jfieldID psi_fdID;
  63 jfieldID psi_addressID;
  64 jfieldID psi_ipaddressID;
  65 jfieldID psi_portID;
  66 jfieldID psi_localportID;
  67 jfieldID psi_timeoutID;
  68 jfieldID psi_trafficClassID;
  69 jfieldID psi_serverSocketID;
  70 jfieldID psi_fdLockID;
  71 jfieldID psi_closePendingID;
  72 
  73 extern void setDefaultScopeID(JNIEnv *env, struct sockaddr *him);
  74 
  75 /*
  76  * file descriptor used for dup2
  77  */
  78 static int marker_fd = -1;
  79 
  80 
  81 #define SET_NONBLOCKING(fd) {           \
  82         int flags = fcntl(fd, F_GETFL); \
  83         flags |= O_NONBLOCK;            \
  84         fcntl(fd, F_SETFL, flags);      \
  85 }
  86 
  87 #define SET_BLOCKING(fd) {              \
  88         int flags = fcntl(fd, F_GETFL); \
  89         flags &= ~O_NONBLOCK;           \
  90         fcntl(fd, F_SETFL, flags);      \
  91 }
  92 
  93 /*
  94  * Create the marker file descriptor by establishing a loopback connection
  95  * which we shutdown but do not close the fd. The result is an fd that
  96  * can be used for read/write.
  97  */
  98 static int getMarkerFD()
  99 {
 100     int sv[2];
 101 
 102 #ifdef AF_UNIX
 103     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1) {
 104         return -1;
 105     }
 106 #else
 107     return -1;
 108 #endif
 109 
 110     /*
 111      * Finally shutdown sv[0] (any reads to this fd will get
 112      * EOF; any writes will get an error).
 113      */
 114     JVM_SocketShutdown(sv[0], 2);
 115     JVM_SocketClose(sv[1]);
 116 
 117     return sv[0];
 118 }
 119 
 120 /*
 121  * Return the file descriptor given a PlainSocketImpl
 122  */
 123 static int getFD(JNIEnv *env, jobject this) {
 124     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 125     CHECK_NULL_RETURN(fdObj, -1);
 126     return (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 127 }
 128 
 129 /*
 130  * The initroto function is called whenever PlainSocketImpl is
 131  * loaded, to cache field IDs for efficiency. This is called every time
 132  * the Java class is loaded.
 133  *
 134  * Class:     java_net_PlainSocketImpl
 135  * Method:    initProto
 136  * Signature: ()V
 137  */
 138 JNIEXPORT void JNICALL
 139 Java_java_net_PlainSocketImpl_initProto(JNIEnv *env, jclass cls) {
 140     psi_fdID = (*env)->GetFieldID(env, cls , "fd",
 141                                   "Ljava/io/FileDescriptor;");
 142     CHECK_NULL(psi_fdID);
 143     psi_addressID = (*env)->GetFieldID(env, cls, "address",
 144                                           "Ljava/net/InetAddress;");
 145     CHECK_NULL(psi_addressID);
 146     psi_portID = (*env)->GetFieldID(env, cls, "port", "I");
 147     CHECK_NULL(psi_portID);
 148     psi_localportID = (*env)->GetFieldID(env, cls, "localport", "I");
 149     CHECK_NULL(psi_localportID);
 150     psi_timeoutID = (*env)->GetFieldID(env, cls, "timeout", "I");
 151     CHECK_NULL(psi_timeoutID);
 152     psi_trafficClassID = (*env)->GetFieldID(env, cls, "trafficClass", "I");
 153     CHECK_NULL(psi_trafficClassID);
 154     psi_serverSocketID = (*env)->GetFieldID(env, cls, "serverSocket",
 155                         "Ljava/net/ServerSocket;");
 156     CHECK_NULL(psi_serverSocketID);
 157     psi_fdLockID = (*env)->GetFieldID(env, cls, "fdLock",
 158                                       "Ljava/lang/Object;");
 159     CHECK_NULL(psi_fdLockID);
 160     psi_closePendingID = (*env)->GetFieldID(env, cls, "closePending", "Z");
 161     CHECK_NULL(psi_closePendingID);
 162     IO_fd_fdID = NET_GetFileDescriptorID(env);
 163     CHECK_NULL(IO_fd_fdID);
 164 
 165     initInetAddressIDs(env);
 166     JNU_CHECK_EXCEPTION(env);
 167 
 168     /* Create the marker fd used for dup2 */
 169     marker_fd = getMarkerFD();
 170 }
 171 
 172 /* a global reference to the java.net.SocketException class. In
 173  * socketCreate, we ensure that this is initialized. This is to
 174  * prevent the problem where socketCreate runs out of file
 175  * descriptors, and is then unable to load the exception class.
 176  */
 177 static jclass socketExceptionCls;
 178 
 179 /*
 180  * Class:     java_net_PlainSocketImpl
 181  * Method:    socketCreate
 182  * Signature: (Z)V */
 183 JNIEXPORT void JNICALL
 184 Java_java_net_PlainSocketImpl_socketCreate(JNIEnv *env, jobject this,
 185                                            jboolean stream) {
 186     jobject fdObj, ssObj;
 187     int fd;
 188     int type = (stream ? SOCK_STREAM : SOCK_DGRAM);
 189 #ifdef AF_INET6
 190     int domain = ipv6_available() ? AF_INET6 : AF_INET;
 191 #else
 192     int domain = AF_INET;
 193 #endif
 194 
 195     if (socketExceptionCls == NULL) {
 196         jclass c = (*env)->FindClass(env, "java/net/SocketException");
 197         CHECK_NULL(c);
 198         socketExceptionCls = (jclass)(*env)->NewGlobalRef(env, c);
 199         CHECK_NULL(socketExceptionCls);
 200     }
 201     fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 202 
 203     if (fdObj == NULL) {
 204         (*env)->ThrowNew(env, socketExceptionCls, "null fd object");
 205         return;
 206     }
 207 
 208     if ((fd = JVM_Socket(domain, type, 0)) == JVM_IO_ERR) {
 209         /* note: if you run out of fds, you may not be able to load
 210          * the exception class, and get a NoClassDefFoundError
 211          * instead.
 212          */
 213         NET_ThrowNew(env, errno, "can't create socket");
 214         return;
 215     }
 216 
 217 #ifdef AF_INET6
 218     /* Disable IPV6_V6ONLY to ensure dual-socket support */
 219     if (domain == AF_INET6) {
 220         int arg = 0;
 221         if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&arg,
 222                        sizeof(int)) < 0) {
 223             NET_ThrowNew(env, errno, "cannot set IPPROTO_IPV6");
 224             close(fd);
 225             return;
 226         }
 227     }
 228 #endif /* AF_INET6 */
 229 
 230     /*
 231      * If this is a server socket then enable SO_REUSEADDR
 232      * automatically and set to non blocking.
 233      */
 234     ssObj = (*env)->GetObjectField(env, this, psi_serverSocketID);
 235     if (ssObj != NULL) {
 236         int arg = 1;
 237         SET_NONBLOCKING(fd);
 238         if (JVM_SetSockOpt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&arg,
 239                            sizeof(arg)) < 0) {
 240             NET_ThrowNew(env, errno, "cannot set SO_REUSEADDR");
 241             close(fd);
 242             return;
 243         }
 244     }
 245 
 246     (*env)->SetIntField(env, fdObj, IO_fd_fdID, fd);
 247 }
 248 
 249 /*
 250  * inetAddress is the address object passed to the socket connect
 251  * call.
 252  *
 253  * Class:     java_net_PlainSocketImpl
 254  * Method:    socketConnect
 255  * Signature: (Ljava/net/InetAddress;I)V
 256  */
 257 JNIEXPORT void JNICALL
 258 Java_java_net_PlainSocketImpl_socketConnect(JNIEnv *env, jobject this,
 259                                             jobject iaObj, jint port,
 260                                             jint timeout)
 261 {
 262     jint localport = (*env)->GetIntField(env, this, psi_localportID);
 263     int len = 0;
 264 
 265     /* fdObj is the FileDescriptor field on this */
 266     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 267 
 268     jclass clazz = (*env)->GetObjectClass(env, this);
 269 
 270     jobject fdLock;
 271 
 272     jint trafficClass = (*env)->GetIntField(env, this, psi_trafficClassID);
 273 
 274     /* fd is an int field on iaObj */
 275     jint fd;
 276 
 277     SOCKADDR him;
 278     /* The result of the connection */
 279     int connect_rv = -1;
 280 
 281     if (IS_NULL(fdObj)) {
 282         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Socket closed");
 283         return;
 284     } else {
 285         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 286     }
 287     if (IS_NULL(iaObj)) {
 288         JNU_ThrowNullPointerException(env, "inet address argument null.");
 289         return;
 290     }
 291 
 292     /* connect */
 293     if (NET_InetAddressToSockaddr(env, iaObj, port, (struct sockaddr *)&him, &len, JNI_TRUE) != 0) {
 294       return;
 295     }
 296     setDefaultScopeID(env, (struct sockaddr *)&him);
 297 
 298 #ifdef AF_INET6
 299     if (trafficClass != 0 && ipv6_available()) {
 300         NET_SetTrafficClass((struct sockaddr *)&him, trafficClass);
 301     }
 302 #endif /* AF_INET6 */
 303     if (timeout <= 0) {
 304         connect_rv = NET_Connect(fd, (struct sockaddr *)&him, len);
 305 #ifdef __solaris__
 306         if (connect_rv == JVM_IO_ERR && errno == EINPROGRESS ) {
 307 
 308             /* This can happen if a blocking connect is interrupted by a signal.
 309              * See 6343810.
 310              */
 311             while (1) {
 312 #ifndef USE_SELECT
 313                 {
 314                     struct pollfd pfd;
 315                     pfd.fd = fd;
 316                     pfd.events = POLLOUT;
 317 
 318                     connect_rv = NET_Poll(&pfd, 1, -1);
 319                 }
 320 #else
 321                 {
 322                     fd_set wr, ex;
 323 
 324                     FD_ZERO(&wr);
 325                     FD_SET(fd, &wr);
 326                     FD_ZERO(&ex);
 327                     FD_SET(fd, &ex);
 328 
 329                     connect_rv = NET_Select(fd+1, 0, &wr, &ex, 0);
 330                 }
 331 #endif
 332 
 333                 if (connect_rv == JVM_IO_ERR) {
 334                     if (errno == EINTR) {
 335                         continue;
 336                     } else {
 337                         break;
 338                     }
 339                 }
 340                 if (connect_rv > 0) {
 341                     int optlen;
 342                     /* has connection been established */
 343                     optlen = sizeof(connect_rv);
 344                     if (JVM_GetSockOpt(fd, SOL_SOCKET, SO_ERROR,
 345                                         (void*)&connect_rv, &optlen) <0) {
 346                         connect_rv = errno;
 347                     }
 348 
 349                     if (connect_rv != 0) {
 350                         /* restore errno */
 351                         errno = connect_rv;
 352                         connect_rv = JVM_IO_ERR;
 353                     }
 354                     break;
 355                 }
 356             }
 357         }
 358 #endif
 359     } else {
 360         /*
 361          * A timeout was specified. We put the socket into non-blocking
 362          * mode, connect, and then wait for the connection to be
 363          * established, fail, or timeout.
 364          */
 365         SET_NONBLOCKING(fd);
 366 
 367         /* no need to use NET_Connect as non-blocking */
 368         connect_rv = connect(fd, (struct sockaddr *)&him, len);
 369 
 370         /* connection not established immediately */
 371         if (connect_rv != 0) {
 372             int optlen;
 373             jlong prevTime = JVM_CurrentTimeMillis(env, 0);
 374 
 375             if (errno != EINPROGRESS) {
 376                 NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
 377                              "connect failed");
 378                 SET_BLOCKING(fd);
 379                 return;
 380             }
 381 
 382             /*
 383              * Wait for the connection to be established or a
 384              * timeout occurs. poll/select needs to handle EINTR in
 385              * case lwp sig handler redirects any process signals to
 386              * this thread.
 387              */
 388             while (1) {
 389                 jlong newTime;
 390 #ifndef USE_SELECT
 391                 {
 392                     struct pollfd pfd;
 393                     pfd.fd = fd;
 394                     pfd.events = POLLOUT;
 395 
 396                     errno = 0;
 397                     connect_rv = NET_Poll(&pfd, 1, timeout);
 398                 }
 399 #else
 400                 {
 401                     fd_set wr, ex;
 402                     struct timeval t;
 403 
 404                     t.tv_sec = timeout / 1000;
 405                     t.tv_usec = (timeout % 1000) * 1000;
 406 
 407                     FD_ZERO(&wr);
 408                     FD_SET(fd, &wr);
 409                     FD_ZERO(&ex);
 410                     FD_SET(fd, &ex);
 411 
 412                     errno = 0;
 413                     connect_rv = NET_Select(fd+1, 0, &wr, &ex, &t);
 414                 }
 415 #endif
 416 
 417                 if (connect_rv >= 0) {
 418                     break;
 419                 }
 420                 if (errno != EINTR) {
 421                     break;
 422                 }
 423 
 424                 /*
 425                  * The poll was interrupted so adjust timeout and
 426                  * restart
 427                  */
 428                 newTime = JVM_CurrentTimeMillis(env, 0);
 429                 timeout -= (newTime - prevTime);
 430                 if (timeout <= 0) {
 431                     connect_rv = 0;
 432                     break;
 433                 }
 434                 prevTime = newTime;
 435 
 436             } /* while */
 437 
 438             if (connect_rv == 0) {
 439                 JNU_ThrowByName(env, JNU_JAVANETPKG "SocketTimeoutException",
 440                             "connect timed out");
 441 
 442                 /*
 443                  * Timeout out but connection may still be established.
 444                  * At the high level it should be closed immediately but
 445                  * just in case we make the socket blocking again and
 446                  * shutdown input & output.
 447                  */
 448                 SET_BLOCKING(fd);
 449                 JVM_SocketShutdown(fd, 2);
 450                 return;
 451             }
 452 
 453             /* has connection been established */
 454             optlen = sizeof(connect_rv);
 455             if (JVM_GetSockOpt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
 456                                &optlen) <0) {
 457                 connect_rv = errno;
 458             }
 459         }
 460 
 461         /* make socket blocking again */
 462         SET_BLOCKING(fd);
 463 
 464         /* restore errno */
 465         if (connect_rv != 0) {
 466             errno = connect_rv;
 467             connect_rv = JVM_IO_ERR;
 468         }
 469     }
 470 
 471     /* report the appropriate exception */
 472     if (connect_rv < 0) {
 473 
 474 #ifdef __linux__
 475         /*
 476          * Linux/GNU distribution setup /etc/hosts so that
 477          * InetAddress.getLocalHost gets back the loopback address
 478          * rather than the host address. Thus a socket can be
 479          * bound to the loopback address and the connect will
 480          * fail with EADDRNOTAVAIL. In addition the Linux kernel
 481          * returns the wrong error in this case - it returns EINVAL
 482          * instead of EADDRNOTAVAIL. We handle this here so that
 483          * a more descriptive exception text is used.
 484          */
 485         if (connect_rv == JVM_IO_ERR && errno == EINVAL) {
 486             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 487                 "Invalid argument or cannot assign requested address");
 488             return;
 489         }
 490 #endif
 491         if (connect_rv == JVM_IO_INTR) {
 492             JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException",
 493                             "operation interrupted");
 494 #if defined(EPROTO)
 495         } else if (errno == EPROTO) {
 496             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ProtocolException",
 497                            "Protocol error");


 498 #endif
 499         } else if (errno == ECONNREFUSED) {
 500             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
 501                            "Connection refused");
 502         } else if (errno == ETIMEDOUT) {
 503             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
 504                            "Connection timed out");
 505         } else if (errno == EHOSTUNREACH) {
 506             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "NoRouteToHostException",
 507                            "Host unreachable");
 508         } else if (errno == EADDRNOTAVAIL) {
 509             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "NoRouteToHostException",
 510                              "Address not available");
 511         } else if ((errno == EISCONN) || (errno == EBADF)) {
 512             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 513                             "Socket closed");
 514         } else {
 515             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "connect failed");
 516         }
 517         return;
 518     }
 519 
 520     (*env)->SetIntField(env, fdObj, IO_fd_fdID, fd);
 521 
 522     /* set the remote peer address and port */
 523     (*env)->SetObjectField(env, this, psi_addressID, iaObj);
 524     (*env)->SetIntField(env, this, psi_portID, port);
 525 
 526     /*
 527      * we need to initialize the local port field if bind was called
 528      * previously to the connect (by the client) then localport field
 529      * will already be initialized
 530      */
 531     if (localport == 0) {
 532         /* Now that we're a connected socket, let's extract the port number
 533          * that the system chose for us and store it in the Socket object.
 534          */
 535         len = SOCKADDR_LEN;
 536         if (JVM_GetSockName(fd, (struct sockaddr *)&him, &len) == -1) {
 537             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
 538                            "Error getting socket name");
 539         } else {
 540             localport = NET_GetPortFromSockaddr((struct sockaddr *)&him);
 541             (*env)->SetIntField(env, this, psi_localportID, localport);
 542         }
 543     }
 544 }
 545 
 546 /*
 547  * Class:     java_net_PlainSocketImpl
 548  * Method:    socketBind
 549  * Signature: (Ljava/net/InetAddress;I)V
 550  */
 551 JNIEXPORT void JNICALL
 552 Java_java_net_PlainSocketImpl_socketBind(JNIEnv *env, jobject this,
 553                                          jobject iaObj, jint localport) {
 554 
 555     /* fdObj is the FileDescriptor field on this */
 556     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 557     /* fd is an int field on fdObj */
 558     int fd;
 559     int len;
 560     SOCKADDR him;
 561 
 562     if (IS_NULL(fdObj)) {
 563         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 564                         "Socket closed");
 565         return;
 566     } else {
 567         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 568     }
 569     if (IS_NULL(iaObj)) {
 570         JNU_ThrowNullPointerException(env, "iaObj is null.");
 571         return;
 572     }
 573 
 574     /* bind */
 575     if (NET_InetAddressToSockaddr(env, iaObj, localport, (struct sockaddr *)&him, &len, JNI_TRUE) != 0) {
 576       return;
 577     }
 578     setDefaultScopeID(env, (struct sockaddr *)&him);
 579 
 580     if (NET_Bind(fd, (struct sockaddr *)&him, len) < 0) {
 581         if (errno == EADDRINUSE || errno == EADDRNOTAVAIL ||
 582             errno == EPERM || errno == EACCES) {
 583             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "BindException",
 584                            "Bind failed");
 585         } else {
 586             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
 587                            "Bind failed");
 588         }
 589         return;
 590     }
 591 
 592     /* set the address */
 593     (*env)->SetObjectField(env, this, psi_addressID, iaObj);
 594 
 595     /* initialize the local port */
 596     if (localport == 0) {

 597         /* Now that we're a connected socket, let's extract the port number
 598          * that the system chose for us and store it in the Socket object.
 599          */
 600         if (JVM_GetSockName(fd, (struct sockaddr *)&him, &len) == -1) {
 601             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
 602                            "Error getting socket name");
 603             return;
 604         }
 605         localport = NET_GetPortFromSockaddr((struct sockaddr *)&him);
 606         (*env)->SetIntField(env, this, psi_localportID, localport);
 607     } else {
 608         (*env)->SetIntField(env, this, psi_localportID, localport);
 609     }
 610 }
 611 
 612 /*
 613  * Class:     java_net_PlainSocketImpl
 614  * Method:    socketListen
 615  * Signature: (I)V
 616  */
 617 JNIEXPORT void JNICALL
 618 Java_java_net_PlainSocketImpl_socketListen (JNIEnv *env, jobject this,
 619                                             jint count)
 620 {
 621     /* this FileDescriptor fd field */
 622     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 623     /* fdObj's int fd field */
 624     int fd;
 625 
 626     if (IS_NULL(fdObj)) {
 627         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 628                         "Socket closed");
 629         return;
 630     } else {
 631         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 632     }
 633 
 634     /*
 635      * Workaround for bugid 4101691 in Solaris 2.6. See 4106600.
 636      * If listen backlog is Integer.MAX_VALUE then subtract 1.
 637      */
 638     if (count == 0x7fffffff)
 639         count -= 1;
 640 
 641     if (JVM_Listen(fd, count) == JVM_IO_ERR) {
 642         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
 643                        "Listen failed");
 644     }
 645 }
 646 
 647 /*
 648  * Class:     java_net_PlainSocketImpl
 649  * Method:    socketAccept
 650  * Signature: (Ljava/net/SocketImpl;)V
 651  */
 652 JNIEXPORT void JNICALL
 653 Java_java_net_PlainSocketImpl_socketAccept(JNIEnv *env, jobject this,
 654                                            jobject socket)
 655 {
 656     /* fields on this */
 657     int port;
 658     jint timeout = (*env)->GetIntField(env, this, psi_timeoutID);
 659     jlong prevTime = 0;
 660     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 661 
 662     /* the FileDescriptor field on socket */
 663     jobject socketFdObj;
 664     /* the InetAddress field on socket */
 665     jobject socketAddressObj;
 666 
 667     /* the ServerSocket fd int field on fdObj */
 668     jint fd;
 669 
 670     /* accepted fd */
 671     jint newfd;
 672 
 673     SOCKADDR him;
 674     int len;
 675 
 676     len = SOCKADDR_LEN;
 677 
 678     if (IS_NULL(fdObj)) {
 679         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 680                         "Socket closed");
 681         return;
 682     } else {
 683         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 684     }
 685     if (IS_NULL(socket)) {
 686         JNU_ThrowNullPointerException(env, "socket is null");
 687         return;
 688     }
 689 
 690     /*
 691      * accept connection but ignore ECONNABORTED indicating that
 692      * connection was eagerly accepted by the OS but was reset
 693      * before accept() was called.
 694      *
 695      * If accept timeout in place and timeout is adjusted with
 696      * each ECONNABORTED or EWOULDBLOCK to ensure that semantics
 697      * of timeout are preserved.
 698      */
 699     for (;;) {
 700         int ret;
 701 
 702         /* first usage pick up current time */
 703         if (prevTime == 0 && timeout > 0) {
 704             prevTime = JVM_CurrentTimeMillis(env, 0);
 705         }
 706 
 707         /* passing a timeout of 0 to poll will return immediately,
 708            but in the case of ServerSocket 0 means infinite. */
 709         if (timeout <= 0) {
 710             ret = NET_Timeout(fd, -1);
 711         } else {
 712             ret = NET_Timeout(fd, timeout);
 713         }
 714 
 715         if (ret == 0) {
 716             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketTimeoutException",
 717                             "Accept timed out");
 718             return;
 719         } else if (ret == JVM_IO_ERR) {
 720             if (errno == EBADF) {
 721                JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Socket closed");
 722             } else {
 723                NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "Accept failed");
 724             }
 725             return;
 726         } else if (ret == JVM_IO_INTR) {
 727             JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException",
 728                             "operation interrupted");
 729             return;
 730         }
 731 
 732         newfd = NET_Accept(fd, (struct sockaddr *)&him, (jint*)&len);
 733 
 734         /* connection accepted */
 735         if (newfd >= 0) {
 736             SET_BLOCKING(newfd);
 737             break;
 738         }
 739 
 740         /* non (ECONNABORTED or EWOULDBLOCK) error */
 741         if (!(errno == ECONNABORTED || errno == EWOULDBLOCK)) {
 742             break;
 743         }
 744 
 745         /* ECONNABORTED or EWOULDBLOCK error so adjust timeout if there is one. */
 746         if (timeout) {
 747             jlong currTime = JVM_CurrentTimeMillis(env, 0);
 748             timeout -= (currTime - prevTime);
 749 
 750             if (timeout <= 0) {
 751                 JNU_ThrowByName(env, JNU_JAVANETPKG "SocketTimeoutException",
 752                                 "Accept timed out");
 753                 return;
 754             }
 755             prevTime = currTime;
 756         }
 757     }
 758 
 759     if (newfd < 0) {
 760         if (newfd == -2) {
 761             JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException",
 762                             "operation interrupted");
 763         } else {
 764             if (errno == EINVAL) {
 765                 errno = EBADF;
 766             }
 767             if (errno == EBADF) {
 768                 JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Socket closed");
 769             } else {
 770                 NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "Accept failed");
 771             }
 772         }
 773         return;
 774     }
 775 
 776     /*
 777      * fill up the remote peer port and address in the new socket structure.
 778      */
 779     socketAddressObj = NET_SockaddrToInetAddress(env, (struct sockaddr *)&him, &port);
 780     if (socketAddressObj == NULL) {
 781         /* should be pending exception */
 782         close(newfd);
 783         return;
 784     }
 785 
 786     /*
 787      * Populate SocketImpl.fd.fd
 788      */
 789     socketFdObj = (*env)->GetObjectField(env, socket, psi_fdID);
 790     (*env)->SetIntField(env, socketFdObj, IO_fd_fdID, newfd);
 791 
 792     (*env)->SetObjectField(env, socket, psi_addressID, socketAddressObj);
 793     (*env)->SetIntField(env, socket, psi_portID, port);
 794     /* also fill up the local port information */
 795      port = (*env)->GetIntField(env, this, psi_localportID);
 796     (*env)->SetIntField(env, socket, psi_localportID, port);
 797 }
 798 
 799 
 800 /*
 801  * Class:     java_net_PlainSocketImpl
 802  * Method:    socketAvailable
 803  * Signature: ()I
 804  */
 805 JNIEXPORT jint JNICALL
 806 Java_java_net_PlainSocketImpl_socketAvailable(JNIEnv *env, jobject this) {
 807 
 808     jint ret = -1;
 809     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 810     jint fd;
 811 
 812     if (IS_NULL(fdObj)) {
 813         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 814                         "Socket closed");
 815         return -1;
 816     } else {
 817         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 818     }
 819     /* JVM_SocketAvailable returns 0 for failure, 1 for success */
 820     if (!JVM_SocketAvailable(fd, &ret)){
 821         if (errno == ECONNRESET) {
 822             JNU_ThrowByName(env, "sun/net/ConnectionResetException", "");
 823         } else {
 824             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
 825                                          "ioctl FIONREAD failed");
 826         }
 827     }
 828     return ret;
 829 }
 830 
 831 /*
 832  * Class:     java_net_PlainSocketImpl
 833  * Method:    socketClose0
 834  * Signature: (Z)V
 835  */
 836 JNIEXPORT void JNICALL
 837 Java_java_net_PlainSocketImpl_socketClose0(JNIEnv *env, jobject this,
 838                                           jboolean useDeferredClose) {
 839 
 840     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 841     jint fd;
 842 
 843     if (IS_NULL(fdObj)) {
 844         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 845                         "socket already closed");
 846         return;
 847     } else {
 848         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 849     }
 850     if (fd != -1) {
 851         if (useDeferredClose && marker_fd >= 0) {
 852             NET_Dup2(marker_fd, fd);
 853         } else {
 854             (*env)->SetIntField(env, fdObj, IO_fd_fdID, -1);
 855             NET_SocketClose(fd);
 856         }
 857     }
 858 }
 859 
 860 /*
 861  * Class:     java_net_PlainSocketImpl
 862  * Method:    socketShutdown
 863  * Signature: (I)V
 864  */
 865 JNIEXPORT void JNICALL
 866 Java_java_net_PlainSocketImpl_socketShutdown(JNIEnv *env, jobject this,
 867                                              jint howto)
 868 {
 869 
 870     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 871     jint fd;
 872 
 873     /*
 874      * WARNING: THIS NEEDS LOCKING. ALSO: SHOULD WE CHECK for fd being
 875      * -1 already?
 876      */
 877     if (IS_NULL(fdObj)) {
 878         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 879                         "socket already closed");
 880         return;
 881     } else {
 882         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 883     }
 884     JVM_SocketShutdown(fd, howto);
 885 }
 886 
 887 
 888 /*
 889  * Class:     java_net_PlainSocketImpl
 890  * Method:    socketSetOption
 891  * Signature: (IZLjava/lang/Object;)V
 892  */
 893 JNIEXPORT void JNICALL
 894 Java_java_net_PlainSocketImpl_socketSetOption(JNIEnv *env, jobject this,
 895                                               jint cmd, jboolean on,
 896                                               jobject value) {
 897     int fd;
 898     int level, optname, optlen;
 899     union {
 900         int i;
 901         struct linger ling;
 902     } optval;
 903 
 904     /*
 905      * Check that socket hasn't been closed
 906      */
 907     fd = getFD(env, this);
 908     if (fd < 0) {
 909         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 910                         "Socket closed");
 911         return;
 912     }
 913 
 914     /*
 915      * SO_TIMEOUT is a NOOP on Solaris/Linux
 916      */
 917     if (cmd == java_net_SocketOptions_SO_TIMEOUT) {
 918         return;
 919     }
 920 
 921     /*
 922      * Map the Java level socket option to the platform specific
 923      * level and option name.
 924      */
 925     if (NET_MapSocketOption(cmd, &level, &optname)) {
 926         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Invalid option");
 927         return;
 928     }
 929 
 930     switch (cmd) {
 931         case java_net_SocketOptions_SO_SNDBUF :
 932         case java_net_SocketOptions_SO_RCVBUF :
 933         case java_net_SocketOptions_SO_LINGER :
 934         case java_net_SocketOptions_IP_TOS :
 935             {
 936                 jclass cls;
 937                 jfieldID fid;
 938 
 939                 cls = (*env)->FindClass(env, "java/lang/Integer");
 940                 CHECK_NULL(cls);
 941                 fid = (*env)->GetFieldID(env, cls, "value", "I");
 942                 CHECK_NULL(fid);
 943 
 944                 if (cmd == java_net_SocketOptions_SO_LINGER) {
 945                     if (on) {
 946                         optval.ling.l_onoff = 1;
 947                         optval.ling.l_linger = (*env)->GetIntField(env, value, fid);
 948                     } else {
 949                         optval.ling.l_onoff = 0;
 950                         optval.ling.l_linger = 0;
 951                     }
 952                     optlen = sizeof(optval.ling);
 953                 } else {
 954                     optval.i = (*env)->GetIntField(env, value, fid);
 955                     optlen = sizeof(optval.i);
 956                 }
 957 
 958                 break;
 959             }
 960 
 961         /* Boolean -> int */
 962         default :
 963             optval.i = (on ? 1 : 0);
 964             optlen = sizeof(optval.i);
 965 
 966     }
 967 
 968     if (NET_SetSockOpt(fd, level, optname, (const void *)&optval, optlen) < 0) {
 969 #if defined(__solaris__) || defined(_AIX)
 970         if (errno == EINVAL) {
 971             // On Solaris setsockopt will set errno to EINVAL if the socket
 972             // is closed. The default error message is then confusing
 973             char fullMsg[128];
 974             jio_snprintf(fullMsg, sizeof(fullMsg), "Invalid option or socket reset by remote peer");
 975             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", fullMsg);
 976             return;
 977         }
 978 #endif /* __solaris__ */
 979         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
 980                                       "Error setting socket option");
 981     }
 982 }
 983 
 984 /*
 985  * Class:     java_net_PlainSocketImpl
 986  * Method:    socketGetOption
 987  * Signature: (I)I
 988  */
 989 JNIEXPORT jint JNICALL
 990 Java_java_net_PlainSocketImpl_socketGetOption(JNIEnv *env, jobject this,
 991                                               jint cmd, jobject iaContainerObj) {
 992 
 993     int fd;
 994     int level, optname, optlen;
 995     union {
 996         int i;
 997         struct linger ling;
 998     } optval;
 999 
1000     /*
1001      * Check that socket hasn't been closed
1002      */
1003     fd = getFD(env, this);
1004     if (fd < 0) {
1005         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
1006                         "Socket closed");
1007         return -1;
1008     }
1009 
1010     /*
1011      * SO_BINDADDR isn't a socket option
1012      */
1013     if (cmd == java_net_SocketOptions_SO_BINDADDR) {
1014         SOCKADDR him;
1015         socklen_t len = 0;
1016         int port;
1017         jobject iaObj;
1018         jclass iaCntrClass;
1019         jfieldID iaFieldID;
1020 
1021         len = SOCKADDR_LEN;
1022 
1023         if (getsockname(fd, (struct sockaddr *)&him, &len) < 0) {
1024             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1025                              "Error getting socket name");
1026             return -1;
1027         }
1028         iaObj = NET_SockaddrToInetAddress(env, (struct sockaddr *)&him, &port);
1029         CHECK_NULL_RETURN(iaObj, -1);
1030 
1031         iaCntrClass = (*env)->GetObjectClass(env, iaContainerObj);
1032         iaFieldID = (*env)->GetFieldID(env, iaCntrClass, "addr", "Ljava/net/InetAddress;");
1033         CHECK_NULL_RETURN(iaFieldID, -1);
1034         (*env)->SetObjectField(env, iaContainerObj, iaFieldID, iaObj);
1035         return 0; /* notice change from before */
1036     }
1037 
1038     /*
1039      * Map the Java level socket option to the platform specific
1040      * level and option name.
1041      */
1042     if (NET_MapSocketOption(cmd, &level, &optname)) {
1043         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Invalid option");
1044         return -1;
1045     }
1046 
1047     /*
1048      * Args are int except for SO_LINGER
1049      */
1050     if (cmd == java_net_SocketOptions_SO_LINGER) {
1051         optlen = sizeof(optval.ling);
1052     } else {
1053         optlen = sizeof(optval.i);
1054     }
1055 
1056     if (NET_GetSockOpt(fd, level, optname, (void *)&optval, &optlen) < 0) {
1057         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1058                                       "Error getting socket option");
1059         return -1;
1060     }
1061 
1062     switch (cmd) {
1063         case java_net_SocketOptions_SO_LINGER:
1064             return (optval.ling.l_onoff ? optval.ling.l_linger: -1);
1065 
1066         case java_net_SocketOptions_SO_SNDBUF:
1067         case java_net_SocketOptions_SO_RCVBUF:
1068         case java_net_SocketOptions_IP_TOS:
1069             return optval.i;
1070 
1071         default :
1072             return (optval.i == 0) ? -1 : 1;
1073     }
1074 }
1075 
1076 
1077 /*
1078  * Class:     java_net_PlainSocketImpl
1079  * Method:    socketSendUrgentData
1080  * Signature: (B)V
1081  */
1082 JNIEXPORT void JNICALL
1083 Java_java_net_PlainSocketImpl_socketSendUrgentData(JNIEnv *env, jobject this,
1084                                              jint data) {
1085     /* The fd field */
1086     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
1087     int n, fd;
1088     unsigned char d = data & 0xFF;
1089 
1090     if (IS_NULL(fdObj)) {
1091         JNU_ThrowByName(env, "java/net/SocketException", "Socket closed");
1092         return;
1093     } else {
1094         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
1095         /* Bug 4086704 - If the Socket associated with this file descriptor
1096          * was closed (sysCloseFD), the the file descriptor is set to -1.
1097          */
1098         if (fd == -1) {
1099             JNU_ThrowByName(env, "java/net/SocketException", "Socket closed");
1100             return;
1101         }
1102 
1103     }
1104     n = JVM_Send(fd, (char *)&d, 1, MSG_OOB);
1105     if (n == JVM_IO_ERR) {
1106         NET_ThrowByNameWithLastError(env, "java/io/IOException", "Write failed");
1107         return;
1108     }
1109     if (n == JVM_IO_INTR) {
1110         JNU_ThrowByName(env, "java/io/InterruptedIOException", 0);
1111         return;
1112     }
1113 }
--- EOF ---