private static void checkConnect(URL url) { SecurityManager security = System.getSecurityManager(); if (security != null) { try { j86.java.security.Permission perm = url.openConnection().getPermission(); if (perm != null) security.checkPermission(perm); else security.checkConnect(url.getHost(), url.getPort()); } catch (j86.java.io.IOException ioe) { security.checkConnect(url.getHost(), url.getPort()); } } }
/** * Same as {@link #openConnection()}, except that the connection will be made through the * specified proxy; Protocol handlers that do not support proxing will ignore the proxy parameter * and make a normal connection. * * <p>Invoking this method preempts the system's default ProxySelector settings. * * @param proxy the Proxy through which this connection will be made. If direct connection is * desired, Proxy.NO_PROXY should be specified. * @return a <code>URLConnection</code> to the URL. * @exception IOException if an I/O exception occurs. * @exception SecurityException if a security manager is present and the caller doesn't have * permission to connect to the proxy. * @exception IllegalArgumentException will be thrown if proxy is null, or proxy has the wrong * type * @exception UnsupportedOperationException if the subclass that implements the protocol handler * doesn't support this method. * @see java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String) * @see java.net.URLConnection * @see java.net.URLStreamHandler#openConnection(java.net.URL, java.net.Proxy) * @since 1.5 */ public URLConnection openConnection(Proxy proxy) throws java.io.IOException { if (proxy == null) { throw new IllegalArgumentException("proxy can not be null"); } SecurityManager sm = System.getSecurityManager(); if (proxy.type() != Proxy.Type.DIRECT && sm != null) { InetSocketAddress epoint = (InetSocketAddress) proxy.address(); if (epoint.isUnresolved()) sm.checkConnect(epoint.getHostName(), epoint.getPort()); else sm.checkConnect(epoint.getAddress().getHostAddress(), epoint.getPort()); } return handler.openConnection(this, proxy); }
private static synchronized void getLocalHost(SecurityManager s) throws UnknownHostException { // Check the localhost cache again, now that we've synchronized. if (s == null && localhost != null) return; String hostname = getLocalHostname(); if (s != null) { // "The Java Class Libraries" suggests that if the security // manager disallows getting the local host name, then // we use the loopback host. // However, the JDK 1.2 API claims to throw SecurityException, // which seems to suggest SecurityException is *not* caught. // In this case, experimentation shows that former is correct. try { // This is wrong, if the name returned from getLocalHostname() // is not a fully qualified name. FIXME. s.checkConnect(hostname, -1); } catch (SecurityException ex) { hostname = null; } } if (hostname != null && hostname.length() != 0) { try { localhost = new InetAddress(null, null); lookup(hostname, localhost, false); } catch (Exception ex) { } } else throw new UnknownHostException(); if (localhost == null) localhost = new InetAddress(loopbackAddress, "localhost"); }
private static InetAddress[] getAllByName0(String host, InetAddress reqAddr, boolean check) throws UnknownHostException { /* If it gets here it is presumed to be a hostname */ /* Cache.get can return: null, unknownAddress, or InetAddress[] */ Object obj = null; Object objcopy = null; /* make sure the connection to the host is allowed, before we * give out a hostname */ if (check) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkConnect(host, -1); } } obj = getCachedAddress(host); /* If no entry in cache, then do the host lookup */ if (obj == null) { obj = getAddressFromNameService(host, reqAddr); } if (obj == unknown_array) throw new UnknownHostException(host); /* Make a copy of the InetAddress array */ objcopy = ((InetAddress[]) obj).clone(); return (InetAddress[]) objcopy; }
static HttpClient New( SSLSocketFactory sf, URL url, HostnameVerifier hv, String proxy, int proxyPort, boolean useCache) throws IOException { HttpsClient ret = null; if (useCache) { /* see if one's already around */ ret = (HttpsClient) kac.get(url, sf); if (ret != null) { ret.cachedHttpClient = true; } } if (ret == null) { ret = new HttpsClient(sf, url, proxy, proxyPort); } else { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkConnect(url.getHost(), url.getPort()); } ret.url = url; } ret.setHostnameVerifier(hv); return ret; }
public DatagramChannel connect(SocketAddress sa) throws IOException { int localPort = 0; synchronized (readLock) { synchronized (writeLock) { synchronized (stateLock) { ensureOpenAndUnconnected(); InetSocketAddress isa = Net.checkAddress(sa); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); int n = Net.connect(family, fd, isa.getAddress(), isa.getPort()); if (n <= 0) throw new Error(); // Can't happen // Connection succeeded; disallow further invocation state = ST_CONNECTED; remoteAddress = sa; sender = isa; cachedSenderInetAddress = isa.getAddress(); cachedSenderPort = isa.getPort(); // set or refresh local address localAddress = Net.localAddress(fd); } } } return this; }
/** * Gets the host name of this IP address. If the IP address could not be resolved, the textual * representation in a dotted-quad-notation is returned. * * @return the corresponding string name of this IP address. */ public String getHostName() { try { if (hostName == null) { int address = 0; if (ipaddress.length == 4) { address = bytesToInt(ipaddress, 0); if (address == 0) { return hostName = ipAddressToString(ipaddress); } } hostName = getHostByAddrImpl(ipaddress).hostName; if (hostName.equals("localhost") && ipaddress.length == 4 // $NON-NLS-1$ && address != 0x7f000001) { return hostName = ipAddressToString(ipaddress); } } } catch (UnknownHostException e) { return hostName = ipAddressToString(ipaddress); } SecurityManager security = System.getSecurityManager(); try { // Only check host names, not addresses if (security != null && isHostName(hostName)) { security.checkConnect(hostName, -1); } } catch (SecurityException e) { return ipAddressToString(ipaddress); } return hostName; }
/** * Gets the fully qualified domain name for the host associated with this IP address. If a * security manager is set, it is checked if the method caller is allowed to get the hostname. * Otherwise, the textual representation in a dotted-quad-notation is returned. * * @return the fully qualified domain name of this IP address. */ public String getCanonicalHostName() { String canonicalName; try { int address = 0; if (ipaddress.length == 4) { address = bytesToInt(ipaddress, 0); if (address == 0) { return ipAddressToString(ipaddress); } } canonicalName = getHostByAddrImpl(ipaddress).hostName; } catch (UnknownHostException e) { return ipAddressToString(ipaddress); } SecurityManager security = System.getSecurityManager(); try { // Only check host names, not addresses if (security != null && isHostName(canonicalName)) { security.checkConnect(canonicalName, -1); } } catch (SecurityException e) { return ipAddressToString(ipaddress); } return canonicalName; }
private JarFile getCachedJarFile(URL url) { JarFile result = (JarFile) fileCache.get(url); /* if the JAR file is cached, the permission will always be there */ if (result != null) { Permission perm = getPermission(result); if (perm != null) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { try { sm.checkPermission(perm); } catch (SecurityException se) { // fallback to checkRead/checkConnect for pre 1.2 // security managers if ((perm instanceof java.io.FilePermission) && perm.getActions().indexOf("read") != -1) { sm.checkRead(perm.getName()); } else if ((perm instanceof java.net.SocketPermission) && perm.getActions().indexOf("connect") != -1) { sm.checkConnect(url.getHost(), url.getPort()); } else { throw se; } } } } } return result; }
/** * Returns an InetAddress object representing the IP address of the given hostname. This name can * be either a hostname such as "www.urbanophile.com" or an IP address in dotted decimal format * such as "127.0.0.1". If the hostname is null or "", the hostname of the local machine is * supplied by default. This method is equivalent to returning the first element in the * InetAddress array returned from GetAllByName. * * @param hostname The name of the desired host, or null for the local loopback address. * @return The address of the host as an InetAddress object. * @exception UnknownHostException If no IP address for the host could be found * @exception SecurityException If a security manager exists and its checkConnect method doesn't * allow the operation */ public static InetAddress getByName(String hostname) throws UnknownHostException { // If null or the empty string is supplied, the loopback address // is returned. Note that this is permitted without a security check. if (hostname == null || hostname.length() == 0) return loopback; SecurityManager s = System.getSecurityManager(); if (s != null) s.checkConnect(hostname, -1); // Assume that the host string is an IP address byte[] address = aton(hostname); if (address != null) { if (address.length == 4) return new Inet4Address(address, null); else if (address.length == 16) { if ((address[10] == 0xFF) && (address[11] == 0xFF)) { byte[] ip4addr = new byte[4]; ip4addr[0] = address[12]; ip4addr[1] = address[13]; ip4addr[2] = address[14]; ip4addr[3] = address[15]; return new Inet4Address(ip4addr, null); } return new Inet6Address(address, null); } else throw new UnknownHostException("Address has invalid length"); } // Try to resolve the host by DNS InetAddress result = new InetAddress(null, null); lookup(hostname, result, false); return result; }
/* * Check whether the resource URL should be returned. * Throw exception on failure. * Called internally within this file. */ static void check(URL url) throws IOException { SecurityManager security = System.getSecurityManager(); if (security != null) { URLConnection urlConnection = url.openConnection(); Permission perm = urlConnection.getPermission(); if (perm != null) { try { security.checkPermission(perm); } catch (SecurityException se) { // fallback to checkRead/checkConnect for pre 1.2 // security managers if ((perm instanceof java.io.FilePermission) && perm.getActions().indexOf("read") != -1) { security.checkRead(perm.getName()); } else if ((perm instanceof java.net.SocketPermission) && perm.getActions().indexOf("connect") != -1) { URL locUrl = url; if (urlConnection instanceof JarURLConnection) { locUrl = ((JarURLConnection) urlConnection).getJarFileURL(); } security.checkConnect(locUrl.getHost(), locUrl.getPort()); } else { throw se; } } } } }
/** * Gets a list of addresses bound to this network interface. * * @return the address list of the represented network interface. */ public Enumeration<InetAddress> getInetAddresses() { /* * create new vector from which Enumeration to be returned can be * generated set the initial capacity to be the number of addresses for * the network interface which is the maximum required size */ /* * return an empty enumeration if there are no addresses associated with * the interface */ if (addresses == null) { return new Vector<InetAddress>(0).elements(); } /* * for those configuration that support the security manager we only * return addresses for which checkConnect returns true */ Vector<InetAddress> accessibleAddresses = new Vector<InetAddress>(addresses.length); /* * get the security manager. If one does not exist just return the full * list */ SecurityManager security = System.getSecurityManager(); if (security == null) { return (new Vector<InetAddress>(Arrays.asList(addresses))).elements(); } /* * ok security manager exists so check each address and return those * that pass */ for (InetAddress element : addresses) { if (security != null) { try { /* * since we don't have a port in this case we pass in * NO_PORT */ String hostName = element.getHostName(); if (hostName.contains("::")) { hostName = getFullFormOfCompressedIPV6Address(hostName); } security.checkConnect(hostName, CHECK_CONNECT_NO_PORT); accessibleAddresses.add(element); } catch (SecurityException e) { } } } Enumeration<InetAddress> theAccessibleElements = accessibleAddresses.elements(); if (theAccessibleElements.hasMoreElements()) { return accessibleAddresses.elements(); } return new Vector<InetAddress>(0).elements(); }
public boolean connect(SocketAddress sa) throws IOException { int trafficClass = 0; // ## Pick up from options int localPort = 0; synchronized (readLock) { synchronized (writeLock) { ensureOpenAndUnconnected(); InetSocketAddress isa = Net.checkAddress(sa); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); synchronized (blockingLock()) { int n = 0; try { try { begin(); synchronized (stateLock) { if (!isOpen()) { return false; } readerThread = NativeThread.current(); } for (; ; ) { InetAddress ia = isa.getAddress(); if (ia.isAnyLocalAddress()) ia = InetAddress.getLocalHost(); n = connectImpl(ia, isa.getPort(), trafficClass); if ((n == IOStatus.INTERRUPTED) && isOpen()) continue; break; } } finally { readerCleanup(); end((n > 0) || (n == IOStatus.UNAVAILABLE)); assert IOStatus.check(n); } } catch (IOException x) { // If an exception was thrown, close the channel after // invoking end() so as to avoid bogus // AsynchronousCloseExceptions close(); throw x; } synchronized (stateLock) { remoteAddress = isa; if (n > 0) { // Connection succeeded; disallow further // invocation state = ST_CONNECTED; return true; } // If nonblocking and no exception then connection // pending; disallow another invocation if (!isBlocking()) state = ST_PENDING; else assert false; } } return false; } } }
@Override <A> Future<Void> implConnect( SocketAddress remote, A attachment, CompletionHandler<Void, ? super A> handler) { if (!isOpen()) { Throwable exc = new ClosedChannelException(); if (handler == null) return CompletedFuture.withFailure(exc); Invoker.invoke(this, handler, attachment, null, exc); return null; } InetSocketAddress isa = Net.checkAddress(remote); // permission check SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); // check and update state // ConnectEx requires the socket to be bound to a local address IOException bindException = null; synchronized (stateLock) { if (state == ST_CONNECTED) throw new AlreadyConnectedException(); if (state == ST_PENDING) throw new ConnectionPendingException(); if (localAddress == null) { try { bind(new InetSocketAddress(0)); } catch (IOException x) { bindException = x; } } if (bindException == null) state = ST_PENDING; } // handle bind failure if (bindException != null) { try { close(); } catch (IOException ignore) { } if (handler == null) return CompletedFuture.withFailure(bindException); Invoker.invoke(this, handler, attachment, null, bindException); return null; } // setup task PendingFuture<Void, A> result = new PendingFuture<Void, A>(this, handler, attachment); ConnectTask task = new ConnectTask<A>(isa, result); result.setContext(task); // initiate I/O if (Iocp.supportsThreadAgnosticIo()) { task.run(); } else { Invoker.invokeOnThreadInThreadPool(this, task); } return result; }
/* Helper function due to a CNI limitation. */ private static SecurityException checkConnect(String hostname) { SecurityManager s = System.getSecurityManager(); if (s == null) return null; try { s.checkConnect(hostname, -1); return null; } catch (SecurityException ex) { return ex; } }
/** * Returns an {@code InetAddress} for the local host if possible, or the loopback address * otherwise. This method works by getting the hostname, performing a DNS lookup, and then taking * the first returned address. For devices with multiple network interfaces and/or multiple * addresses per interface, this does not necessarily return the {@code InetAddress} you want. * * <p>Multiple interface/address configurations were relatively rare when this API was designed, * but multiple interfaces are the default for modern mobile devices (with separate wifi and radio * interfaces), and the need to support both IPv4 and IPv6 has made multiple addresses * commonplace. New code should thus avoid this method except where it's basically being used to * get a loopback address or equivalent. * * <p>There are two main ways to get a more specific answer: * * <ul> * <li>If you have a connected socket, you should probably use {@link Socket#getLocalAddress} * instead: that will give you the address that's actually in use for that connection. (It's * not possible to ask the question "what local address would a connection to a given remote * address use?"; you have to actually make the connection and see.) * <li>For other use cases, see {@link NetworkInterface}, which lets you enumerate all available * network interfaces and their addresses. * </ul> * * <p>Note that if the host doesn't have a hostname set – as Android devices typically * don't – this method will effectively return the loopback address, albeit by getting * the name {@code localhost} and then doing a lookup to translate that to {@code 127.0.0.1}. * * @return an {@code InetAddress} representing the local host, or the loopback address. * @throws UnknownHostException if the address lookup fails. */ public static InetAddress getLocalHost() throws UnknownHostException { String host = gethostname(); SecurityManager security = System.getSecurityManager(); try { if (security != null) { security.checkConnect(host, -1); } } catch (SecurityException e) { return Inet4Address.LOOPBACK; } return lookupHostByName(host)[0]; }
/** * Returns the hostname for this address. * * <p>If there is a security manager, this method first calls its <code>checkConnect</code> method * with the hostname and <code>-1</code> as its arguments to see if the calling code is allowed to * know the hostname for this IP address, i.e., to connect to the host. If the operation is not * allowed, it will return the textual representation of the IP address. * * @return the host name for this IP address, or if the operation is not allowed by the security * check, the textual representation of the IP address. * @param check make security check if true * @see SecurityManager#checkConnect */ private static String getHostFromNameService(InetAddress addr, boolean check) { String host = null; for (NameService nameService : nameServices) { try { // first lookup the hostname host = nameService.getHostByAddr(addr.getAddress()); /* check to see if calling code is allowed to know * the hostname for this IP address, ie, connect to the host */ if (check) { SecurityManager sec = System.getSecurityManager(); if (sec != null) { sec.checkConnect(host, -1); } } /* now get all the IP addresses for this hostname, * and make sure one of them matches the original IP * address. We do this to try and prevent spoofing. */ InetAddress[] arr = InetAddress.getAllByName0(host, check); boolean ok = false; if (arr != null) { for (int i = 0; !ok && i < arr.length; i++) { ok = addr.equals(arr[i]); } } // XXX: if it looks a spoof just return the address? if (!ok) { host = addr.getHostAddress(); return host; } break; } catch (SecurityException e) { host = addr.getHostAddress(); break; } catch (UnknownHostException e) { host = addr.getHostAddress(); // let next provider resolve the hostname } } return host; }
public int send(ByteBuffer src, SocketAddress target) throws IOException { if (src == null) throw new NullPointerException(); synchronized (writeLock) { ensureOpen(); InetSocketAddress isa = Net.checkAddress(target); InetAddress ia = isa.getAddress(); if (ia == null) throw new IOException("Target address not resolved"); synchronized (stateLock) { if (!isConnected()) { if (target == null) throw new NullPointerException(); SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (ia.isMulticastAddress()) { sm.checkMulticast(ia); } else { sm.checkConnect(ia.getHostAddress(), isa.getPort()); } } } else { // Connected case; Check address then write if (!target.equals(remoteAddress)) { throw new IllegalArgumentException("Connected address not equal to target address"); } return write(src); } } int n = 0; try { begin(); if (!isOpen()) return 0; writerThread = NativeThread.current(); do { n = send(fd, src, isa); } while ((n == IOStatus.INTERRUPTED) && isOpen()); synchronized (stateLock) { if (isOpen() && (localAddress == null)) { localAddress = Net.localAddress(fd); } } return IOStatus.normalize(n); } finally { writerThread = 0; end((n > 0) || (n == IOStatus.UNAVAILABLE)); assert IOStatus.check(n); } } }
static String getHostNameInternal(String host, boolean isCheck) throws UnknownHostException { if (host == null || 0 == host.length()) { return Inet4Address.LOOPBACK.getHostAddress(); } if (isHostName(host)) { if (isCheck) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkConnect(host, -1); } } return lookupHostByName(host)[0].getHostAddress(); } return host; }
@Override public DatagramChannel connect(SocketAddress sa) throws IOException { int localPort = 0; synchronized (readLock) { synchronized (writeLock) { synchronized (stateLock) { ensureOpenAndUnconnected(); InetSocketAddress isa = Net.checkAddress(sa); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); int n = Net.connect(family, fd, isa.getAddress(), isa.getPort()); if (n <= 0) throw new Error(); // Can't happen // Connection succeeded; disallow further invocation state = ST_CONNECTED; remoteAddress = isa; sender = isa; cachedSenderInetAddress = isa.getAddress(); cachedSenderPort = isa.getPort(); // set or refresh local address localAddress = Net.localAddress(fd); // flush any packets already received. boolean blocking = false; synchronized (blockingLock()) { try { blocking = isBlocking(); // remainder of each packet thrown away ByteBuffer tmpBuf = ByteBuffer.allocate(1); if (blocking) { configureBlocking(false); } do { tmpBuf.clear(); } while (receive(tmpBuf) != null); } finally { if (blocking) { configureBlocking(true); } } } } } } return this; }
/** * Gets the local address to which the socket is bound. * * <p>If there is a security manager, its <code>checkConnect</code> method is first called with * the host address and <code>-1</code> as its arguments to see if the operation is allowed. * * @see SecurityManager#checkConnect * @return the local address to which the socket is bound, <code>null</code> if the socket is * closed, or an <code>InetAddress</code> representing {@link InetAddress#isAnyLocalAddress * wildcard} address if either the socket is not bound, or the security manager <code> * checkConnect</code> method does not allow the operation * @since 1.1 */ public InetAddress getLocalAddress() { if (isClosed()) return null; InetAddress in = null; try { in = (InetAddress) getImpl().getOption(SocketOptions.SO_BINDADDR); if (in.isAnyLocalAddress()) { in = InetAddress.anyLocalAddress(); } SecurityManager s = System.getSecurityManager(); if (s != null) { s.checkConnect(in.getHostAddress(), -1); } } catch (Exception e) { in = InetAddress.anyLocalAddress(); // "0.0.0.0" } return in; }
/** * Sends a datagram packet to the destination, with a TTL (time- to-live) other than the default * for the socket. This method need only be used in instances where a particular TTL is desired; * otherwise it is preferable to set a TTL once on the socket, and use that default TTL for all * packets. This method does <B>not </B> alter the default TTL for the socket. Its behavior may be * affected by {@code setInterface}. * * <p>If there is a security manager, this method first performs some security checks. First, if * {@code p.getAddress().isMulticastAddress()} is true, this method calls the security manager's * {@code checkMulticast} method with {@code p.getAddress()} and {@code ttl} as its arguments. If * the evaluation of that expression is false, this method instead calls the security manager's * {@code checkConnect} method with arguments {@code p.getAddress().getHostAddress()} and {@code * p.getPort()}. Each call to a security manager method could result in a SecurityException if the * operation is not allowed. * * @param p is the packet to be sent. The packet should contain the destination multicast ip * address and the data to be sent. One does not need to be the member of the group to send * packets to a destination multicast address. * @param ttl optional time to live for multicast packet. default ttl is 1. * @exception IOException is raised if an error occurs i.e error while setting ttl. * @exception SecurityException if a security manager exists and its {@code checkMulticast} or * {@code checkConnect} method doesn't allow the send. * @deprecated Use the following code or its equivalent instead: ...... int ttl = * mcastSocket.getTimeToLive(); mcastSocket.setTimeToLive(newttl); mcastSocket.send(p); * mcastSocket.setTimeToLive(ttl); ...... * @see DatagramSocket#send * @see DatagramSocket#receive * @see SecurityManager#checkMulticast(java.net.InetAddress, byte) * @see SecurityManager#checkConnect */ @Deprecated public void send(DatagramPacket p, byte ttl) throws IOException { if (isClosed()) throw new SocketException("Socket is closed"); checkAddress(p.getAddress(), "send"); synchronized (ttlLock) { synchronized (p) { if (connectState == ST_NOT_CONNECTED) { // Security manager makes sure that the multicast address // is allowed one and that the ttl used is less // than the allowed maxttl. SecurityManager security = System.getSecurityManager(); if (security != null) { if (p.getAddress().isMulticastAddress()) { security.checkMulticast(p.getAddress(), ttl); } else { security.checkConnect(p.getAddress().getHostAddress(), p.getPort()); } } } else { // we're connected InetAddress packetAddress = null; packetAddress = p.getAddress(); if (packetAddress == null) { p.setAddress(connectedAddress); p.setPort(connectedPort); } else if ((!packetAddress.equals(connectedAddress)) || p.getPort() != connectedPort) { throw new SecurityException("connected address and packet address" + " differ"); } } byte dttl = getTTL(); try { if (ttl != dttl) { // set the ttl getImpl().setTTL(ttl); } // call the datagram method to send getImpl().send(p); } finally { // set it back to default if (ttl != dttl) { getImpl().setTTL(dttl); } } } // synch p } // synch ttl } // method
@Override public boolean connect(SocketAddress addr) throws IOException { int trafficClass = 0; ensureOpenAndUnconnected(); InetSocketAddress isa = LinuxSocketImpl.checkAddress(addr); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); synchronized (_regLock) { int res = 0; try { synchronized (_stateLock) { if (!isOpen()) { return false; } } for (; ; ) { InetAddress ia = isa.getAddress(); if (ia.isAnyLocalAddress()) ia = InetAddress.getLocalHost(); res = LinuxSocketImpl.connect(_fd, ia, isa.getPort(), trafficClass); if ((res == LinuxSocketImpl.INTERRUPTED) && isOpen()) continue; break; } } catch (IOException e) { close(); throw e; } synchronized (_stateLock) { _remoteAddress = isa; if (res > 0) { _state = State.Connected; return true; } if (!isBlocking()) _state = State.Pending; else assert false; } } return false; }
public static boolean useBridge(URI uri) { LOG.fine("Determine whether bridge needs to be used"); try { SecurityManager securityManager = System.getSecurityManager(); if (securityManager != null) { String host = uri.getHost(); int port = uri.getPort(); securityManager.checkConnect(host, port); } LOG.fine("Bypassing the bridge: " + uri); return false; } catch (Exception e) { LOG.fine("Must use bridge: " + uri + ": " + e.getMessage()); return true; } }
public DatagramChannel disconnect() throws IOException { synchronized (readLock) { synchronized (writeLock) { synchronized (stateLock) { if (!isConnected() || !isOpen()) return this; InetSocketAddress isa = (InetSocketAddress) remoteAddress; SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); disconnect0(fd); remoteAddress = null; state = ST_UNCONNECTED; // refresh local address localAddress = Net.localAddress(fd); } } } return this; }
/** * Returns an array of InetAddress objects representing all the host/ip addresses of a given host, * given the host's name. This name can be either a hostname such as "www.urbanophile.com" or an * IP address in dotted decimal format such as "127.0.0.1". If the value is null, the hostname of * the local machine is supplied by default. * * @param hostname The name of the desired host, or null for the local loopback address. * @return All addresses of the host as an array of InetAddress objects. * @exception UnknownHostException If no IP address for the host could be found * @exception SecurityException If a security manager exists and its checkConnect method doesn't * allow the operation */ public static InetAddress[] getAllByName(String hostname) throws UnknownHostException { // If null or the empty string is supplied, the loopback address // is returned. Note that this is permitted without a security check. if (hostname == null || hostname.length() == 0) return new InetAddress[] {loopback}; SecurityManager s = System.getSecurityManager(); if (s != null) s.checkConnect(hostname, -1); // Check if hostname is an IP address byte[] address = aton(hostname); if (address != null) { InetAddress[] result = new InetAddress[1]; result[0] = new InetAddress(address, null); return result; } // Try to resolve the hostname by DNS return lookup(hostname, null, true); }
/** * Returns the canonical hostname represented by this InetAddress * * @since 1.4 */ public String getCanonicalHostName() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { try { sm.checkConnect(hostName, -1); } catch (SecurityException e) { return getHostAddress(); } } // Try to find the FDQN now InetAddress address; byte[] ipaddr = getAddress(); if (ipaddr.length == 16) address = new Inet6Address(getAddress(), null); else address = new Inet4Address(getAddress(), null); return address.getHostName(); }
/** * Returns the address of the local host. This is achieved by retrieving the name of the host from * the system, then resolving that name into an <code>InetAddress</code>. * * <p>Note: The resolved address may be cached for a short period of time. * * <p>If there is a security manager, its <code>checkConnect</code> method is called with the * local host name and <code>-1</code> as its arguments to see if the operation is allowed. If the * operation is not allowed, an InetAddress representing the loopback address is returned. * * @return the address of the local host. * @exception UnknownHostException if the local host name could not be resolved into an address. * @see SecurityManager#checkConnect * @see java.net.InetAddress#getByName(java.lang.String) */ public static InetAddress getLocalHost() throws UnknownHostException { SecurityManager security = System.getSecurityManager(); try { String local = impl.getLocalHostName(); if (security != null) { security.checkConnect(local, -1); } if (local.equals("localhost")) { return impl.loopbackAddress(); } InetAddress ret = null; synchronized (cacheLock) { long now = System.currentTimeMillis(); if (cachedLocalHost != null) { if ((now - cacheTime) < maxCacheTime) // Less than 5s old? ret = cachedLocalHost; else cachedLocalHost = null; } // we are calling getAddressFromNameService directly // to avoid getting localHost from cache if (ret == null) { InetAddress[] localAddrs; try { localAddrs = (InetAddress[]) InetAddress.getAddressFromNameService(local, null); } catch (UnknownHostException uhe) { throw new UnknownHostException(local + ": " + uhe.getMessage()); } cachedLocalHost = localAddrs[0]; cacheTime = now; ret = localAddrs[0]; } } return ret; } catch (java.lang.SecurityException e) { return impl.loopbackAddress(); } }
/** * This constructor is where the real work takes place. Connect to the specified address and port. * Use default local values if not specified, otherwise use the local host and port passed in. * Create as stream or datagram based on "stream" argument. * * <p> * * @param raddr The remote address to connect to * @param rport The remote port to connect to * @param laddr The local address to connect to * @param lport The local port to connect to * @param stream true for a stream socket, false for a datagram socket * @exception IOException If an error occurs * @exception SecurityException If a security manager exists and its checkConnect method doesn't * allow the operation */ private Socket(InetAddress raddr, int rport, InetAddress laddr, int lport, boolean stream) throws IOException { this(); this.inputShutdown = false; this.outputShutdown = false; if (impl == null) throw new IOException("Cannot initialize Socket implementation"); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(raddr.getHostName(), rport); impl.create(stream); // FIXME: JCL p. 1586 says if localPort is unspecified, bind to any port, // i.e. '0' and if localAddr is unspecified, use getLocalAddress() as // that default. JDK 1.2 doc infers not to do a bind. if (laddr != null) impl.bind(laddr, lport); if (raddr != null) impl.connect(raddr, rport); }
/** * {@collect.stats} {@description.open} Connects this socket to a remote socket address (IP * address + port number). Binds socket if not already bound. * * <p>{@description.close} * * @param addr The remote address. * @param port The remote port * @throws SocketException if binding the socket fails. */ private synchronized void connectInternal(InetAddress address, int port) throws SocketException { if (port < 0 || port > 0xFFFF) { throw new IllegalArgumentException("connect: " + port); } if (address == null) { throw new IllegalArgumentException("connect: null address"); } checkAddress(address, "connect"); if (isClosed()) return; SecurityManager security = System.getSecurityManager(); if (security != null) { if (address.isMulticastAddress()) { security.checkMulticast(address); } else { security.checkConnect(address.getHostAddress(), port); security.checkAccept(address.getHostAddress(), port); } } if (!isBound()) bind(new InetSocketAddress(0)); // old impls do not support connect/disconnect if (oldImpl) { connectState = ST_CONNECTED_NO_IMPL; } else { try { getImpl().connect(address, port); // socket is now connected by the impl connectState = ST_CONNECTED; } catch (SocketException se) { // connection will be emulated by DatagramSocket connectState = ST_CONNECTED_NO_IMPL; } } connectedAddress = address; connectedPort = port; }