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     shutdown(sv[0], 2);
 115     close(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 = socket(domain, type, 0)) == -1) {
 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 (NET_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 == -1 && 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 == -1) {
 334                     if (errno == EINTR) {
 335                         continue;
 336                     } else {
 337                         break;
 338                     }
 339                 }
 340                 if (connect_rv > 0) {
 341                     socklen_t optlen;
 342                     /* has connection been established */
 343                     optlen = sizeof(connect_rv);
 344                     if (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 = -1;
 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             socklen_t 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                 shutdown(fd, 2);
 450                 return;
 451             }
 452 
 453             /* has connection been established */
 454             optlen = sizeof(connect_rv);
 455             if (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 = -1;
 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 == -1 && errno == EINVAL) {
 486             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 487                 "Invalid argument or cannot assign requested address");
 488             return;
 489         }
 490 #endif
 491 #if defined(EPROTO)
 492         if (errno == EPROTO) {
 493             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ProtocolException",
 494                            "Protocol error");
 495             return;
 496         }
 497 #endif
 498         if (errno == ECONNREFUSED) {
 499             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
 500                            "Connection refused");
 501         } else if (errno == ETIMEDOUT) {
 502             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
 503                            "Connection timed out");
 504         } else if (errno == EHOSTUNREACH) {
 505             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "NoRouteToHostException",
 506                            "Host unreachable");
 507         } else if (errno == EADDRNOTAVAIL) {
 508             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "NoRouteToHostException",
 509                              "Address not available");
 510         } else if ((errno == EISCONN) || (errno == EBADF)) {
 511             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 512                             "Socket closed");
 513         } else {
 514             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "connect failed");
 515         }
 516         return;
 517     }
 518 
 519     (*env)->SetIntField(env, fdObj, IO_fd_fdID, fd);
 520 
 521     /* set the remote peer address and port */
 522     (*env)->SetObjectField(env, this, psi_addressID, iaObj);
 523     (*env)->SetIntField(env, this, psi_portID, port);
 524 
 525     /*
 526      * we need to initialize the local port field if bind was called
 527      * previously to the connect (by the client) then localport field
 528      * will already be initialized
 529      */
 530     if (localport == 0) {
 531         /* Now that we're a connected socket, let's extract the port number
 532          * that the system chose for us and store it in the Socket object.
 533          */
 534         socklen_t slen = SOCKADDR_LEN;
 535         if (getsockname(fd, (struct sockaddr *)&him, &slen) == -1) {
 536             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
 537                            "Error getting socket name");
 538         } else {
 539             localport = NET_GetPortFromSockaddr((struct sockaddr *)&him);
 540             (*env)->SetIntField(env, this, psi_localportID, localport);
 541         }
 542     }
 543 }
 544 
 545 /*
 546  * Class:     java_net_PlainSocketImpl
 547  * Method:    socketBind
 548  * Signature: (Ljava/net/InetAddress;I)V
 549  */
 550 JNIEXPORT void JNICALL
 551 Java_java_net_PlainSocketImpl_socketBind(JNIEnv *env, jobject this,
 552                                          jobject iaObj, jint localport) {
 553 
 554     /* fdObj is the FileDescriptor field on this */
 555     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 556     /* fd is an int field on fdObj */
 557     int fd;
 558     int len;
 559     SOCKADDR him;
 560 
 561     if (IS_NULL(fdObj)) {
 562         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 563                         "Socket closed");
 564         return;
 565     } else {
 566         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 567     }
 568     if (IS_NULL(iaObj)) {
 569         JNU_ThrowNullPointerException(env, "iaObj is null.");
 570         return;
 571     }
 572 
 573     /* bind */
 574     if (NET_InetAddressToSockaddr(env, iaObj, localport, (struct sockaddr *)&him, &len, JNI_TRUE) != 0) {
 575       return;
 576     }
 577     setDefaultScopeID(env, (struct sockaddr *)&him);
 578 
 579     if (NET_Bind(fd, (struct sockaddr *)&him, len) < 0) {
 580         if (errno == EADDRINUSE || errno == EADDRNOTAVAIL ||
 581             errno == EPERM || errno == EACCES) {
 582             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "BindException",
 583                            "Bind failed");
 584         } else {
 585             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
 586                            "Bind failed");
 587         }
 588         return;
 589     }
 590 
 591     /* set the address */
 592     (*env)->SetObjectField(env, this, psi_addressID, iaObj);
 593 
 594     /* initialize the local port */
 595     if (localport == 0) {
 596         socklen_t slen = sizeof(him);
 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 (getsockname(fd, (struct sockaddr *)&him, &slen) == -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 (listen(fd, count) == -1) {
 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     socklen_t slen = SOCKADDR_LEN;
 675 
 676     if (IS_NULL(fdObj)) {
 677         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 678                         "Socket closed");
 679         return;
 680     } else {
 681         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 682     }
 683     if (IS_NULL(socket)) {
 684         JNU_ThrowNullPointerException(env, "socket is null");
 685         return;
 686     }
 687 
 688     /*
 689      * accept connection but ignore ECONNABORTED indicating that
 690      * connection was eagerly accepted by the OS but was reset
 691      * before accept() was called.
 692      *
 693      * If accept timeout in place and timeout is adjusted with
 694      * each ECONNABORTED or EWOULDBLOCK to ensure that semantics
 695      * of timeout are preserved.
 696      */
 697     for (;;) {
 698         int ret;
 699 
 700         /* first usage pick up current time */
 701         if (prevTime == 0 && timeout > 0) {
 702             prevTime = JVM_CurrentTimeMillis(env, 0);
 703         }
 704 
 705         /* passing a timeout of 0 to poll will return immediately,
 706            but in the case of ServerSocket 0 means infinite. */
 707         if (timeout <= 0) {
 708             ret = NET_Timeout(env, fd, -1);
 709         } else {
 710             ret = NET_Timeout(env, fd, timeout);
 711         }
 712         JNU_CHECK_EXCEPTION(env);
 713         if (ret == 0) {
 714             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketTimeoutException",
 715                             "Accept timed out");
 716             return;
 717         } else if (ret == -1) {
 718             if (errno == EBADF) {
 719                JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Socket closed");
 720             } else {
 721                NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "Accept failed");
 722             }
 723             return;
 724         }
 725 
 726         newfd = NET_Accept(fd, (struct sockaddr *)&him, &slen);
 727 
 728         /* connection accepted */
 729         if (newfd >= 0) {
 730             SET_BLOCKING(newfd);
 731             break;
 732         }
 733 
 734         /* non (ECONNABORTED or EWOULDBLOCK) error */
 735         if (!(errno == ECONNABORTED || errno == EWOULDBLOCK)) {
 736             break;
 737         }
 738 
 739         /* ECONNABORTED or EWOULDBLOCK error so adjust timeout if there is one. */
 740         if (timeout) {
 741             jlong currTime = JVM_CurrentTimeMillis(env, 0);
 742             timeout -= (currTime - prevTime);
 743 
 744             if (timeout <= 0) {
 745                 JNU_ThrowByName(env, JNU_JAVANETPKG "SocketTimeoutException",
 746                                 "Accept timed out");
 747                 return;
 748             }
 749             prevTime = currTime;
 750         }
 751     }
 752 
 753     if (newfd < 0) {
 754         if (newfd == -2) {
 755             JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException",
 756                             "operation interrupted");
 757         } else {
 758             if (errno == EINVAL) {
 759                 errno = EBADF;
 760             }
 761             if (errno == EBADF) {
 762                 JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Socket closed");
 763             } else {
 764                 NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "Accept failed");
 765             }
 766         }
 767         return;
 768     }
 769 
 770     /*
 771      * fill up the remote peer port and address in the new socket structure.
 772      */
 773     socketAddressObj = NET_SockaddrToInetAddress(env, (struct sockaddr *)&him, &port);
 774     if (socketAddressObj == NULL) {
 775         /* should be pending exception */
 776         close(newfd);
 777         return;
 778     }
 779 
 780     /*
 781      * Populate SocketImpl.fd.fd
 782      */
 783     socketFdObj = (*env)->GetObjectField(env, socket, psi_fdID);
 784     (*env)->SetIntField(env, socketFdObj, IO_fd_fdID, newfd);
 785 
 786     (*env)->SetObjectField(env, socket, psi_addressID, socketAddressObj);
 787     (*env)->SetIntField(env, socket, psi_portID, port);
 788     /* also fill up the local port information */
 789      port = (*env)->GetIntField(env, this, psi_localportID);
 790     (*env)->SetIntField(env, socket, psi_localportID, port);
 791 }
 792 
 793 
 794 /*
 795  * Class:     java_net_PlainSocketImpl
 796  * Method:    socketAvailable
 797  * Signature: ()I
 798  */
 799 JNIEXPORT jint JNICALL
 800 Java_java_net_PlainSocketImpl_socketAvailable(JNIEnv *env, jobject this) {
 801 
 802     jint ret = -1;
 803     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 804     jint fd;
 805 
 806     if (IS_NULL(fdObj)) {
 807         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 808                         "Socket closed");
 809         return -1;
 810     } else {
 811         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 812     }
 813     /* NET_SocketAvailable returns 0 for failure, 1 for success */
 814     if (NET_SocketAvailable(fd, &ret) == 0){
 815         if (errno == ECONNRESET) {
 816             JNU_ThrowByName(env, "sun/net/ConnectionResetException", "");
 817         } else {
 818             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
 819                                          "ioctl FIONREAD failed");
 820         }
 821     }
 822     return ret;
 823 }
 824 
 825 /*
 826  * Class:     java_net_PlainSocketImpl
 827  * Method:    socketClose0
 828  * Signature: (Z)V
 829  */
 830 JNIEXPORT void JNICALL
 831 Java_java_net_PlainSocketImpl_socketClose0(JNIEnv *env, jobject this,
 832                                           jboolean useDeferredClose) {
 833 
 834     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 835     jint fd;
 836 
 837     if (IS_NULL(fdObj)) {
 838         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 839                         "socket already closed");
 840         return;
 841     } else {
 842         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 843     }
 844     if (fd != -1) {
 845         if (useDeferredClose && marker_fd >= 0) {
 846             NET_Dup2(marker_fd, fd);
 847         } else {
 848             (*env)->SetIntField(env, fdObj, IO_fd_fdID, -1);
 849             NET_SocketClose(fd);
 850         }
 851     }
 852 }
 853 
 854 /*
 855  * Class:     java_net_PlainSocketImpl
 856  * Method:    socketShutdown
 857  * Signature: (I)V
 858  */
 859 JNIEXPORT void JNICALL
 860 Java_java_net_PlainSocketImpl_socketShutdown(JNIEnv *env, jobject this,
 861                                              jint howto)
 862 {
 863 
 864     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
 865     jint fd;
 866 
 867     /*
 868      * WARNING: THIS NEEDS LOCKING. ALSO: SHOULD WE CHECK for fd being
 869      * -1 already?
 870      */
 871     if (IS_NULL(fdObj)) {
 872         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 873                         "socket already closed");
 874         return;
 875     } else {
 876         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
 877     }
 878     shutdown(fd, howto);
 879 }
 880 
 881 
 882 /*
 883  * Class:     java_net_PlainSocketImpl
 884  * Method:    socketSetOption
 885  * Signature: (IZLjava/lang/Object;)V
 886  */
 887 JNIEXPORT void JNICALL
 888 Java_java_net_PlainSocketImpl_socketSetOption(JNIEnv *env, jobject this,
 889                                               jint cmd, jboolean on,
 890                                               jobject value) {
 891     int fd;
 892     int level, optname, optlen;
 893     union {
 894         int i;
 895         struct linger ling;
 896     } optval;
 897 
 898     /*
 899      * Check that socket hasn't been closed
 900      */
 901     fd = getFD(env, this);
 902     if (fd < 0) {
 903         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
 904                         "Socket closed");
 905         return;
 906     }
 907 
 908     /*
 909      * SO_TIMEOUT is a NOOP on Solaris/Linux
 910      */
 911     if (cmd == java_net_SocketOptions_SO_TIMEOUT) {
 912         return;
 913     }
 914 
 915     /*
 916      * Map the Java level socket option to the platform specific
 917      * level and option name.
 918      */
 919     if (NET_MapSocketOption(cmd, &level, &optname)) {
 920         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Invalid option");
 921         return;
 922     }
 923 
 924     switch (cmd) {
 925         case java_net_SocketOptions_SO_SNDBUF :
 926         case java_net_SocketOptions_SO_RCVBUF :
 927         case java_net_SocketOptions_SO_LINGER :
 928         case java_net_SocketOptions_IP_TOS :
 929             {
 930                 jclass cls;
 931                 jfieldID fid;
 932 
 933                 cls = (*env)->FindClass(env, "java/lang/Integer");
 934                 CHECK_NULL(cls);
 935                 fid = (*env)->GetFieldID(env, cls, "value", "I");
 936                 CHECK_NULL(fid);
 937 
 938                 if (cmd == java_net_SocketOptions_SO_LINGER) {
 939                     if (on) {
 940                         optval.ling.l_onoff = 1;
 941                         optval.ling.l_linger = (*env)->GetIntField(env, value, fid);
 942                     } else {
 943                         optval.ling.l_onoff = 0;
 944                         optval.ling.l_linger = 0;
 945                     }
 946                     optlen = sizeof(optval.ling);
 947                 } else {
 948                     optval.i = (*env)->GetIntField(env, value, fid);
 949                     optlen = sizeof(optval.i);
 950                 }
 951 
 952                 break;
 953             }
 954 
 955         /* Boolean -> int */
 956         default :
 957             optval.i = (on ? 1 : 0);
 958             optlen = sizeof(optval.i);
 959 
 960     }
 961 
 962     if (NET_SetSockOpt(fd, level, optname, (const void *)&optval, optlen) < 0) {
 963 #if defined(__solaris__) || defined(_AIX)
 964         if (errno == EINVAL) {
 965             // On Solaris setsockopt will set errno to EINVAL if the socket
 966             // is closed. The default error message is then confusing
 967             char fullMsg[128];
 968             jio_snprintf(fullMsg, sizeof(fullMsg), "Invalid option or socket reset by remote peer");
 969             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", fullMsg);
 970             return;
 971         }
 972 #endif /* __solaris__ */
 973         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
 974                                       "Error setting socket option");
 975     }
 976 }
 977 
 978 /*
 979  * Class:     java_net_PlainSocketImpl
 980  * Method:    socketGetOption
 981  * Signature: (I)I
 982  */
 983 JNIEXPORT jint JNICALL
 984 Java_java_net_PlainSocketImpl_socketGetOption(JNIEnv *env, jobject this,
 985                                               jint cmd, jobject iaContainerObj) {
 986 
 987     int fd;
 988     int level, optname, optlen;
 989     union {
 990         int i;
 991         struct linger ling;
 992     } optval;
 993 
 994     /*
 995      * Check that socket hasn't been closed
 996      */
 997     fd = getFD(env, this);
 998     if (fd < 0) {
 999         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
1000                         "Socket closed");
1001         return -1;
1002     }
1003 
1004     /*
1005      * SO_BINDADDR isn't a socket option
1006      */
1007     if (cmd == java_net_SocketOptions_SO_BINDADDR) {
1008         SOCKADDR him;
1009         socklen_t len = 0;
1010         int port;
1011         jobject iaObj;
1012         jclass iaCntrClass;
1013         jfieldID iaFieldID;
1014 
1015         len = SOCKADDR_LEN;
1016 
1017         if (getsockname(fd, (struct sockaddr *)&him, &len) < 0) {
1018             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1019                              "Error getting socket name");
1020             return -1;
1021         }
1022         iaObj = NET_SockaddrToInetAddress(env, (struct sockaddr *)&him, &port);
1023         CHECK_NULL_RETURN(iaObj, -1);
1024 
1025         iaCntrClass = (*env)->GetObjectClass(env, iaContainerObj);
1026         iaFieldID = (*env)->GetFieldID(env, iaCntrClass, "addr", "Ljava/net/InetAddress;");
1027         CHECK_NULL_RETURN(iaFieldID, -1);
1028         (*env)->SetObjectField(env, iaContainerObj, iaFieldID, iaObj);
1029         return 0; /* notice change from before */
1030     }
1031 
1032     /*
1033      * Map the Java level socket option to the platform specific
1034      * level and option name.
1035      */
1036     if (NET_MapSocketOption(cmd, &level, &optname)) {
1037         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Invalid option");
1038         return -1;
1039     }
1040 
1041     /*
1042      * Args are int except for SO_LINGER
1043      */
1044     if (cmd == java_net_SocketOptions_SO_LINGER) {
1045         optlen = sizeof(optval.ling);
1046     } else {
1047         optlen = sizeof(optval.i);
1048     }
1049 
1050     if (NET_GetSockOpt(fd, level, optname, (void *)&optval, &optlen) < 0) {
1051         NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
1052                                       "Error getting socket option");
1053         return -1;
1054     }
1055 
1056     switch (cmd) {
1057         case java_net_SocketOptions_SO_LINGER:
1058             return (optval.ling.l_onoff ? optval.ling.l_linger: -1);
1059 
1060         case java_net_SocketOptions_SO_SNDBUF:
1061         case java_net_SocketOptions_SO_RCVBUF:
1062         case java_net_SocketOptions_IP_TOS:
1063             return optval.i;
1064 
1065         default :
1066             return (optval.i == 0) ? -1 : 1;
1067     }
1068 }
1069 
1070 
1071 /*
1072  * Class:     java_net_PlainSocketImpl
1073  * Method:    socketSendUrgentData
1074  * Signature: (B)V
1075  */
1076 JNIEXPORT void JNICALL
1077 Java_java_net_PlainSocketImpl_socketSendUrgentData(JNIEnv *env, jobject this,
1078                                              jint data) {
1079     /* The fd field */
1080     jobject fdObj = (*env)->GetObjectField(env, this, psi_fdID);
1081     int n, fd;
1082     unsigned char d = data & 0xFF;
1083 
1084     if (IS_NULL(fdObj)) {
1085         JNU_ThrowByName(env, "java/net/SocketException", "Socket closed");
1086         return;
1087     } else {
1088         fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
1089         /* Bug 4086704 - If the Socket associated with this file descriptor
1090          * was closed (sysCloseFD), the the file descriptor is set to -1.
1091          */
1092         if (fd == -1) {
1093             JNU_ThrowByName(env, "java/net/SocketException", "Socket closed");
1094             return;
1095         }
1096 
1097     }
1098     n = NET_Send(fd, (char *)&d, 1, MSG_OOB);
1099     if (n == -1) {
1100         NET_ThrowByNameWithLastError(env, "java/io/IOException", "Write failed");
1101     }
1102 }