Wrap operations requiring SocketPermission with doPrivileged blocks

Motivation:

Currently Netty does not wrap socket connect, bind, or accept
operations in doPrivileged blocks. Nor does it wrap cases where a dns
lookup might happen.

This prevents an application utilizing the SecurityManager from
isolating SocketPermissions to Netty.

Modifications:

I have introduced a class (SocketUtils) that wraps operations
requiring SocketPermissions in doPrivileged blocks.

Result:

A user of Netty can grant SocketPermissions explicitly to the Netty
jar, without granting it to the rest of their application.
This commit is contained in:
Tim Brooks 2016-12-19 14:13:43 -06:00 committed by Norman Maurer
parent 2d11331591
commit 3344cd21ac
42 changed files with 527 additions and 81 deletions

View File

@ -18,6 +18,7 @@ package io.netty.handler.codec.dns;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.InternetProtocolFamily;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.ThreadLocalRandom;
import org.junit.Test;
@ -69,12 +70,12 @@ public class DefaultDnsRecordEncoderTest {
@Test
public void testOptEcsRecordIpv4() throws Exception {
testOptEcsRecordIp(InetAddress.getByName("1.2.3.4"));
testOptEcsRecordIp(SocketUtils.addressByName("1.2.3.4"));
}
@Test
public void testOptEcsRecordIpv6() throws Exception {
testOptEcsRecordIp(InetAddress.getByName("::0"));
testOptEcsRecordIp(SocketUtils.addressByName("::0"));
}
private static void testOptEcsRecordIp(InetAddress address) throws Exception {

View File

@ -18,6 +18,7 @@ package io.netty.handler.codec.dns;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.internal.SocketUtils;
import org.junit.Assert;
import org.junit.Test;
@ -32,7 +33,7 @@ public class DnsQueryTest {
@Test
public void writeQueryTest() throws Exception {
InetSocketAddress addr = new InetSocketAddress("8.8.8.8", 53);
InetSocketAddress addr = SocketUtils.socketAddress("8.8.8.8", 53);
EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsQueryEncoder());
List<DnsQuery> queries = new ArrayList<DnsQuery>(5);
queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(

View File

@ -16,11 +16,11 @@
package io.netty.handler.codec.socks;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import java.net.InetAddress;
import java.net.UnknownHostException;
import static org.junit.Assert.*;
@ -65,7 +65,7 @@ public class SocksCmdRequestDecoderTest {
@Test
public void testCmdRequestDecoderIPv6() throws UnknownHostException {
String[] hosts = {SocksCommonUtils.ipv6toStr(InetAddress.getByName("::1").getAddress())};
String[] hosts = {SocksCommonUtils.ipv6toStr(SocketUtils.addressByName("::1").getAddress())};
int[] ports = {1, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {

View File

@ -17,12 +17,12 @@ package io.netty.handler.codec.socksx.v5;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.NetUtil;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import java.net.IDN;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
@ -68,7 +68,7 @@ public class Socks5CommandRequestDecoderTest {
@Test
public void testCmdRequestDecoderIPv6() throws UnknownHostException {
String[] hosts = {
NetUtil.bytesToIpAddress(InetAddress.getByName("::1").getAddress()) };
NetUtil.bytesToIpAddress(SocketUtils.addressByName("::1").getAddress()) };
int[] ports = {1, 32769, 65535};
for (Socks5CommandType cmdType: Arrays.asList(Socks5CommandType.BIND,
Socks5CommandType.CONNECT,

View File

@ -21,6 +21,7 @@ import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.SocketUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -49,8 +50,8 @@ public class DatagramPacketDecoderTest {
@Test
public void testDecode() {
InetSocketAddress recipient = new InetSocketAddress("127.0.0.1", 10000);
InetSocketAddress sender = new InetSocketAddress("127.0.0.1", 20000);
InetSocketAddress recipient = SocketUtils.socketAddress("127.0.0.1", 10000);
InetSocketAddress sender = SocketUtils.socketAddress("127.0.0.1", 20000);
ByteBuf content = Unpooled.wrappedBuffer("netty".getBytes(CharsetUtil.UTF_8));
assertTrue(channel.writeInbound(new DatagramPacket(content, recipient, sender)));
assertEquals("netty", channel.readInbound());

View File

@ -20,6 +20,7 @@ import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.SocketUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -46,8 +47,8 @@ public class DatagramPacketEncoderTest {
@Test
public void testEncode() {
InetSocketAddress recipient = new InetSocketAddress("127.0.0.1", 10000);
InetSocketAddress sender = new InetSocketAddress("127.0.0.1", 20000);
InetSocketAddress recipient = SocketUtils.socketAddress("127.0.0.1", 10000);
InetSocketAddress sender = SocketUtils.socketAddress("127.0.0.1", 20000);
assertTrue(channel.writeOutbound(
new DefaultAddressedEnvelope<String, InetSocketAddress>("netty", recipient, sender)));
DatagramPacket packet = channel.readOutbound();
@ -62,8 +63,8 @@ public class DatagramPacketEncoderTest {
@Test
public void testUnmatchedMessageType() {
InetSocketAddress recipient = new InetSocketAddress("127.0.0.1", 10000);
InetSocketAddress sender = new InetSocketAddress("127.0.0.1", 20000);
InetSocketAddress recipient = SocketUtils.socketAddress("127.0.0.1", 10000);
InetSocketAddress sender = SocketUtils.socketAddress("127.0.0.1", 20000);
DefaultAddressedEnvelope<Long, InetSocketAddress> envelope =
new DefaultAddressedEnvelope<Long, InetSocketAddress>(1L, recipient, sender);
assertTrue(channel.writeOutbound(envelope));

View File

@ -16,6 +16,7 @@
package io.netty.util;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
@ -165,7 +166,7 @@ public final class NetUtil {
for (Enumeration<NetworkInterface> i = NetworkInterface.getNetworkInterfaces(); i.hasMoreElements();) {
NetworkInterface iface = i.nextElement();
// Use the interface with proper INET addresses only.
if (iface.getInetAddresses().hasMoreElements()) {
if (SocketUtils.addressesFromNetworkInterface(iface).hasMoreElements()) {
ifaces.add(iface);
}
}
@ -179,7 +180,7 @@ public final class NetUtil {
NetworkInterface loopbackIface = null;
InetAddress loopbackAddr = null;
loop: for (NetworkInterface iface: ifaces) {
for (Enumeration<InetAddress> i = iface.getInetAddresses(); i.hasMoreElements();) {
for (Enumeration<InetAddress> i = SocketUtils.addressesFromNetworkInterface(iface); i.hasMoreElements();) {
InetAddress addr = i.nextElement();
if (addr.isLoopbackAddress()) {
// Found
@ -195,7 +196,7 @@ public final class NetUtil {
try {
for (NetworkInterface iface: ifaces) {
if (iface.isLoopback()) {
Enumeration<InetAddress> i = iface.getInetAddresses();
Enumeration<InetAddress> i = SocketUtils.addressesFromNetworkInterface(iface);
if (i.hasMoreElements()) {
// Found the one with INET address.
loopbackIface = iface;

View File

@ -55,7 +55,7 @@ public final class MacAddressUtil {
for (Enumeration<NetworkInterface> i = NetworkInterface.getNetworkInterfaces(); i.hasMoreElements();) {
NetworkInterface iface = i.nextElement();
// Use the interface with proper INET addresses only.
Enumeration<InetAddress> addrs = iface.getInetAddresses();
Enumeration<InetAddress> addrs = SocketUtils.addressesFromNetworkInterface(iface);
if (addrs.hasMoreElements()) {
InetAddress a = addrs.nextElement();
if (!a.isLoopbackAddress()) {
@ -76,7 +76,7 @@ public final class MacAddressUtil {
byte[] macAddr;
try {
macAddr = iface.getHardwareAddress();
macAddr = SocketUtils.hardwareAddressFromNetworkInterface(iface);
} catch (SocketException e) {
logger.debug("Failed to get the hardware address of a network interface: {}", iface, e);
continue;

View File

@ -0,0 +1,197 @@
/*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util.internal;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketPermission;
import java.net.UnknownHostException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Enumeration;
/**
* Provides socket operations with privileges enabled. This is necessary for applications that use the
* {@link SecurityManager} to restrict {@link SocketPermission} to their application. By asserting that these
* operations are privileged, the operations can proceed even if some code in the calling chain lacks the appropriate
* {@link SocketPermission}.
*/
public final class SocketUtils {
private SocketUtils() {
}
public static void connect(final Socket socket, final SocketAddress remoteAddress, final int timeout)
throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
socket.connect(remoteAddress, timeout);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
public static void bind(final Socket socket, final SocketAddress bindpoint) throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
socket.bind(bindpoint);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
public static boolean connect(final SocketChannel socketChannel, final SocketAddress remoteAddress)
throws IOException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
@Override
public Boolean run() throws IOException {
return socketChannel.connect(remoteAddress);
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
public static void bind(final SocketChannel socketChannel, final SocketAddress address) throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
socketChannel.bind(address);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
public static SocketChannel accept(final ServerSocketChannel serverSocketChannel) throws IOException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<SocketChannel>() {
@Override
public SocketChannel run() throws IOException {
return serverSocketChannel.accept();
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
public static void bind(final DatagramChannel networkChannel, final SocketAddress address) throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
networkChannel.bind(address);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
public static SocketAddress localSocketAddress(final ServerSocket socket) {
return AccessController.doPrivileged(new PrivilegedAction<SocketAddress>() {
@Override
public SocketAddress run() {
return socket.getLocalSocketAddress();
}
});
}
public static InetAddress addressByName(final String hostname) throws UnknownHostException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<InetAddress>() {
@Override
public InetAddress run() throws UnknownHostException {
return InetAddress.getByName(hostname);
}
});
} catch (PrivilegedActionException e) {
throw (UnknownHostException) e.getCause();
}
}
public static InetAddress[] allAddressesByName(final String hostname) throws UnknownHostException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<InetAddress[]>() {
@Override
public InetAddress[] run() throws UnknownHostException {
return InetAddress.getAllByName(hostname);
}
});
} catch (PrivilegedActionException e) {
throw (UnknownHostException) e.getCause();
}
}
public static InetSocketAddress socketAddress(final String hostname, final int port) {
return AccessController.doPrivileged(new PrivilegedAction<InetSocketAddress>() {
@Override
public InetSocketAddress run() {
return new InetSocketAddress(hostname, port);
}
});
}
public static Enumeration<InetAddress> addressesFromNetworkInterface(final NetworkInterface intf) {
return AccessController.doPrivileged(new PrivilegedAction<Enumeration<InetAddress>>() {
@Override
public Enumeration<InetAddress> run() {
return intf.getInetAddresses();
}
});
}
public static byte[] hardwareAddressFromNetworkInterface(final NetworkInterface intf) throws SocketException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<byte[]>() {
@Override
public byte[] run() throws SocketException {
return intf.getHardwareAddress();
}
});
} catch (PrivilegedActionException e) {
throw (SocketException) e.getCause();
}
}
}

View File

@ -40,10 +40,10 @@ import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.util.internal.SocketUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.List;
import java.util.Map.Entry;
@ -207,7 +207,7 @@ public final class HttpUploadClient {
List<Entry<String, String>> headers) throws Exception {
// XXX /formpost
// Start the connection attempt.
ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port));
// Wait until the connection attempt succeeds or fails.
Channel channel = future.sync().channel();
@ -267,7 +267,7 @@ public final class HttpUploadClient {
Iterable<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception {
// XXX /formpostmultipart
// Start the connection attempt.
ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(host, port));
// Wait until the connection attempt succeeds or fails.
Channel channel = future.sync().channel();

View File

@ -24,8 +24,7 @@ import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import java.net.InetSocketAddress;
import io.netty.util.internal.SocketUtils;
/**
* A UDP broadcast client that asks for a quote of the moment (QOTM) to {@link QuoteOfTheMomentServer}.
@ -52,7 +51,7 @@ public final class QuoteOfTheMomentClient {
// Broadcast the QOTM request to port 8080.
ch.writeAndFlush(new DatagramPacket(
Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
new InetSocketAddress("255.255.255.255", PORT))).sync();
SocketUtils.socketAddress("255.255.255.255", PORT))).sync();
// QuoteOfTheMomentClientHandler will close the DatagramChannel when a
// response is received. If the channel is not closed within 5 seconds,

View File

@ -24,6 +24,7 @@ import io.netty.channel.sctp.SctpChannel;
import io.netty.channel.sctp.SctpChannelOption;
import io.netty.channel.sctp.nio.NioSctpChannel;
import io.netty.example.sctp.SctpEchoClientHandler;
import io.netty.util.internal.SocketUtils;
import java.net.InetAddress;
import java.net.InetSocketAddress;
@ -58,10 +59,10 @@ public final class SctpMultiHomingEchoClient {
}
});
InetSocketAddress localAddress = new InetSocketAddress(CLIENT_PRIMARY_HOST, CLIENT_PORT);
InetAddress localSecondaryAddress = InetAddress.getByName(CLIENT_SECONDARY_HOST);
InetSocketAddress localAddress = SocketUtils.socketAddress(CLIENT_PRIMARY_HOST, CLIENT_PORT);
InetAddress localSecondaryAddress = SocketUtils.addressByName(CLIENT_SECONDARY_HOST);
InetSocketAddress remoteAddress = new InetSocketAddress(SERVER_REMOTE_HOST, SERVER_REMOTE_PORT);
InetSocketAddress remoteAddress = SocketUtils.socketAddress(SERVER_REMOTE_HOST, SERVER_REMOTE_PORT);
// Bind the client channel.
ChannelFuture bindFuture = b.bind(localAddress).sync();

View File

@ -27,6 +27,7 @@ import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.example.sctp.SctpEchoServerHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.internal.SocketUtils;
import java.net.InetAddress;
import java.net.InetSocketAddress;
@ -60,8 +61,8 @@ public final class SctpMultiHomingEchoServer {
}
});
InetSocketAddress localAddress = new InetSocketAddress(SERVER_PRIMARY_HOST, SERVER_PORT);
InetAddress localSecondaryAddress = InetAddress.getByName(SERVER_SECONDARY_HOST);
InetSocketAddress localAddress = SocketUtils.socketAddress(SERVER_PRIMARY_HOST, SERVER_PORT);
InetAddress localSecondaryAddress = SocketUtils.addressByName(SERVER_SECONDARY_HOST);
// Bind the server to primary address.
ChannelFuture bindFuture = b.bind(localAddress).sync();

View File

@ -15,6 +15,8 @@
*/
package io.netty.example.udt.echo.rendezvous;
import io.netty.util.internal.SocketUtils;
import java.net.InetSocketAddress;
/**
@ -31,8 +33,8 @@ public class MsgEchoPeerOne extends MsgEchoPeerBase {
public static void main(final String[] args) throws Exception {
final int messageSize = 64 * 1024;
final InetSocketAddress self = new InetSocketAddress(Config.hostOne, Config.portOne);
final InetSocketAddress peer = new InetSocketAddress(Config.hostTwo, Config.portTwo);
final InetSocketAddress self = SocketUtils.socketAddress(Config.hostOne, Config.portOne);
final InetSocketAddress peer = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo);
new MsgEchoPeerOne(self, peer, messageSize).run();
}
}

View File

@ -15,6 +15,8 @@
*/
package io.netty.example.udt.echo.rendezvous;
import io.netty.util.internal.SocketUtils;
import java.net.InetSocketAddress;
/**
@ -31,8 +33,8 @@ public class MsgEchoPeerTwo extends MsgEchoPeerBase {
public static void main(final String[] args) throws Exception {
final int messageSize = 64 * 1024;
final InetSocketAddress self = new InetSocketAddress(Config.hostTwo, Config.portTwo);
final InetSocketAddress peer = new InetSocketAddress(Config.hostOne, Config.portOne);
final InetSocketAddress self = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo);
final InetSocketAddress peer = SocketUtils.socketAddress(Config.hostOne, Config.portOne);
new MsgEchoPeerTwo(self, peer, messageSize).run();
}
}

View File

@ -16,6 +16,7 @@
package io.netty.example.udt.echo.rendezvousBytes;
import io.netty.example.udt.echo.rendezvous.Config;
import io.netty.util.internal.SocketUtils;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
@ -37,8 +38,8 @@ public class ByteEchoPeerOne extends ByteEchoPeerBase {
public static void main(String[] args) throws Exception {
final int messageSize = 64 * 1024;
final InetSocketAddress myAddress = new InetSocketAddress(Config.hostOne, Config.portOne);
final InetSocketAddress peerAddress = new InetSocketAddress(Config.hostTwo, Config.portTwo);
final InetSocketAddress myAddress = SocketUtils.socketAddress(Config.hostOne, Config.portOne);
final InetSocketAddress peerAddress = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo);
new ByteEchoPeerOne(messageSize, myAddress, peerAddress).run();
}
}

View File

@ -16,6 +16,7 @@
package io.netty.example.udt.echo.rendezvousBytes;
import io.netty.example.udt.echo.rendezvous.Config;
import io.netty.util.internal.SocketUtils;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
@ -37,8 +38,8 @@ public class ByteEchoPeerTwo extends ByteEchoPeerBase {
public static void main(String[] args) throws Exception {
final int messageSize = 64 * 1024;
final InetSocketAddress myAddress = new InetSocketAddress(Config.hostTwo, Config.portTwo);
final InetSocketAddress peerAddress = new InetSocketAddress(Config.hostOne, Config.portOne);
final InetSocketAddress myAddress = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo);
final InetSocketAddress peerAddress = SocketUtils.socketAddress(Config.hostOne, Config.portOne);
new ByteEchoPeerTwo(messageSize, myAddress, peerAddress).run();
}
}

View File

@ -33,6 +33,7 @@ import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.SocketUtils;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
@ -120,7 +121,7 @@ final class HttpProxyServer extends ProxyServer {
String uri = req.uri();
int lastColonPos = uri.lastIndexOf(':');
assertThat(lastColonPos, is(greaterThan(0)));
intermediaryDestination = new InetSocketAddress(
intermediaryDestination = SocketUtils.socketAddress(
uri.substring(0, lastColonPos), Integer.parseInt(uri.substring(lastColonPos + 1)));
}

View File

@ -39,6 +39,7 @@ import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.resolver.NoopAddressResolverGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.SocketUtils;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.Future;
import io.netty.util.internal.EmptyArrays;
@ -74,7 +75,7 @@ public class ProxyHandlerTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(ProxyHandlerTest.class);
private static final InetSocketAddress DESTINATION = InetSocketAddress.createUnresolved("destination.com", 42);
private static final InetSocketAddress BAD_DESTINATION = new InetSocketAddress("1.2.3.4", 5);
private static final InetSocketAddress BAD_DESTINATION = SocketUtils.socketAddress("1.2.3.4", 5);
private static final String USERNAME = "testUser";
private static final String PASSWORD = "testPassword";
private static final String BAD_USERNAME = "badUser";

View File

@ -29,6 +29,7 @@ import io.netty.handler.codec.socksx.v4.Socks4CommandType;
import io.netty.handler.codec.socksx.v4.Socks4ServerDecoder;
import io.netty.handler.codec.socksx.v4.Socks4ServerEncoder;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.SocketUtils;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
@ -95,7 +96,7 @@ final class Socks4ProxyServer extends ProxyServer {
res = new DefaultSocks4CommandResponse(Socks4CommandStatus.IDENTD_AUTH_FAILURE);
} else {
res = new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS);
intermediaryDestination = new InetSocketAddress(req.dstAddr(), req.dstPort());
intermediaryDestination = SocketUtils.socketAddress(req.dstAddr(), req.dstPort());
}
ctx.write(res);

View File

@ -38,6 +38,7 @@ import io.netty.handler.codec.socksx.v5.Socks5PasswordAuthRequestDecoder;
import io.netty.handler.codec.socksx.v5.Socks5PasswordAuthStatus;
import io.netty.handler.codec.socksx.v5.Socks5ServerEncoder;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.SocketUtils;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
@ -121,7 +122,7 @@ final class Socks5ProxyServer extends ProxyServer {
Socks5CommandResponse res =
new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS, Socks5AddressType.IPv4);
intermediaryDestination = new InetSocketAddress(req.dstAddr(), req.dstPort());
intermediaryDestination = SocketUtils.socketAddress(req.dstAddr(), req.dstPort());
ctx.write(res);

View File

@ -15,6 +15,8 @@
*/
package io.netty.handler.ipfilter;
import io.netty.util.internal.SocketUtils;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.Inet6Address;
@ -32,7 +34,7 @@ public final class IpSubnetFilterRule implements IpFilterRule {
public IpSubnetFilterRule(String ipAddress, int cidrPrefix, IpFilterRuleType ruleType) {
try {
filterRule = selectFilterRule(InetAddress.getByName(ipAddress), cidrPrefix, ruleType);
filterRule = selectFilterRule(SocketUtils.addressByName(ipAddress), cidrPrefix, ruleType);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("ipAddress", e);
}

View File

@ -21,6 +21,7 @@ import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.SocketUtils;
import org.junit.Assert;
import org.junit.Test;
@ -132,12 +133,12 @@ public class IpSubnetFilterTest {
return new EmbeddedChannel(handlers) {
@Override
protected SocketAddress remoteAddress0() {
return isActive()? new InetSocketAddress(ipAddress, 5421) : null;
return isActive()? SocketUtils.socketAddress(ipAddress, 5421) : null;
}
};
}
private static InetSocketAddress newSockAddress(String ipAddress) {
return new InetSocketAddress(ipAddress, 1234);
return SocketUtils.socketAddress(ipAddress, 1234);
}
}

View File

@ -0,0 +1,193 @@
/*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.microbench.internal;
import io.netty.microbench.util.AbstractMicrobenchmark;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.channels.ServerSocketChannel;
import java.security.AccessController;
import java.security.NoSuchAlgorithmException;
import java.security.Policy;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.URIParameter;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public class PrivilegedSocketOperationsBenchmark extends AbstractMicrobenchmark {
@State(Scope.Benchmark)
public static class SecurityManagerInstalled {
@Setup
public void setup() throws IOException, NoSuchAlgorithmException, URISyntaxException {
final URI policyFile = PrivilegedSocketOperationsBenchmark.class.getResource("/jmh-security.policy")
.toURI();
Policy.setPolicy(Policy.getInstance("JavaPolicy", new URIParameter(policyFile)));
System.setSecurityManager(new SecurityManager());
}
@TearDown
public void tearDown() throws IOException {
System.setSecurityManager(null);
}
}
@State(Scope.Benchmark)
public static class SecurityManagerEmpty {
@Setup
public void setup() throws IOException, NoSuchAlgorithmException, URISyntaxException {
System.setSecurityManager(null);
}
}
@Benchmark
public ServerSocketChannel testWithSMNoPrivileged(final SecurityManagerInstalled sm) throws IOException {
final ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(null);
ssc.configureBlocking(false);
ssc.accept();
ssc.close();
return ssc;
}
@Benchmark
public ServerSocketChannel testWithSM(final SecurityManagerInstalled sm) throws IOException {
try {
final ServerSocketChannel ssc = AccessController.doPrivileged(
new PrivilegedExceptionAction<ServerSocketChannel>() {
@Override
public ServerSocketChannel run() throws Exception {
final ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(null);
ssc.configureBlocking(false);
ssc.accept();
return ssc;
}
});
ssc.close();
return ssc;
} catch (final PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
@Benchmark
public ServerSocketChannel testWithSMWithNullCheck(final SecurityManagerInstalled sm) throws IOException {
if (System.getSecurityManager() != null) {
try {
final ServerSocketChannel ssc = AccessController.doPrivileged(
new PrivilegedExceptionAction<ServerSocketChannel>() {
@Override
public ServerSocketChannel run() throws Exception {
final ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(null);
ssc.configureBlocking(false);
ssc.accept();
return ssc;
}
});
ssc.close();
return ssc;
} catch (final PrivilegedActionException e) {
throw (IOException) e.getCause();
}
} else {
// this should never happen during benchmarking, but we write the correct code here
final ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(null);
ssc.configureBlocking(false);
ssc.accept();
ssc.close();
return ssc;
}
}
@Benchmark
public ServerSocketChannel testWithoutSMNoPrivileged(final SecurityManagerEmpty sm) throws IOException {
final ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(null);
ssc.configureBlocking(false);
ssc.accept();
ssc.close();
return ssc;
}
@Benchmark
public ServerSocketChannel testWithoutSM(final SecurityManagerEmpty sm) throws IOException {
try {
final ServerSocketChannel ssc = AccessController.doPrivileged(
new PrivilegedExceptionAction<ServerSocketChannel>() {
@Override
public ServerSocketChannel run() throws Exception {
final ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(null);
ssc.configureBlocking(false);
ssc.accept();
return ssc;
}
});
ssc.close();
return ssc;
} catch (final PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
@Benchmark
public ServerSocketChannel testWithoutSMWithNullCheck(final SecurityManagerEmpty sm) throws IOException {
if (System.getSecurityManager() != null) {
// this should never happen during benchmarking, but we write the correct code here
try {
final ServerSocketChannel ssc = AccessController.doPrivileged(
new PrivilegedExceptionAction<ServerSocketChannel>() {
@Override
public ServerSocketChannel run() throws Exception {
final ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(null);
ssc.configureBlocking(false);
ssc.accept();
return ssc;
}
});
ssc.close();
return ssc;
} catch (final PrivilegedActionException e) {
throw (IOException) e.getCause();
}
} else {
final ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(null);
ssc.configureBlocking(false);
ssc.accept();
ssc.close();
return ssc;
}
}
}

View File

@ -16,12 +16,12 @@
package io.netty.resolver.dns;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.UnstableApi;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
@ -54,7 +54,7 @@ public abstract class DnsServerAddresses {
final List<String> list = (List<String>) nameservers.invoke(instance);
for (String a: list) {
if (a != null) {
defaultNameServers.add(new InetSocketAddress(InetAddress.getByName(a), DNS_PORT));
defaultNameServers.add(new InetSocketAddress(SocketUtils.addressByName(a), DNS_PORT));
}
}
} catch (Exception ignore) {
@ -70,8 +70,8 @@ public abstract class DnsServerAddresses {
} else {
Collections.addAll(
defaultNameServers,
new InetSocketAddress("8.8.8.8", DNS_PORT),
new InetSocketAddress("8.8.4.4", DNS_PORT));
SocketUtils.socketAddress("8.8.8.8", DNS_PORT),
SocketUtils.socketAddress("8.8.4.4", DNS_PORT));
if (logger.isWarnEnabled()) {
logger.warn(

View File

@ -20,12 +20,12 @@ import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.dns.DefaultDnsOptEcsRecord;
import io.netty.handler.codec.dns.DnsRecord;
import io.netty.util.internal.SocketUtils;
import io.netty.util.concurrent.Future;
import org.junit.Ignore;
import org.junit.Test;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
@ -46,7 +46,8 @@ public class DnsNameResolverClientSubnetTest {
Collections.<DnsRecord>singleton(
// Suggest max payload size of 1024
// 157.88.0.0 / 24
new DefaultDnsOptEcsRecord(1024, 24, InetAddress.getByName("157.88.0.0").getAddress())));
new DefaultDnsOptEcsRecord(1024, 24,
SocketUtils.addressByName("157.88.0.0").getAddress())));
for (InetAddress address: future.syncUninterruptibly().getNow()) {
System.err.println(address);
}
@ -59,7 +60,7 @@ public class DnsNameResolverClientSubnetTest {
private static DnsNameResolverBuilder newResolver(EventLoopGroup group) {
return new DnsNameResolverBuilder(group.next())
.channelType(NioDatagramChannel.class)
.nameServerAddresses(DnsServerAddresses.singleton(new InetSocketAddress("8.8.8.8", 53)))
.nameServerAddresses(DnsServerAddresses.singleton(SocketUtils.socketAddress("8.8.8.8", 53)))
.maxQueriesPerResolve(1)
.optResourceEnabled(false);
}

View File

@ -16,6 +16,7 @@
package io.netty.resolver;
import io.netty.util.internal.SocketUtils;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Promise;
@ -37,7 +38,7 @@ public class DefaultNameResolver extends InetNameResolver {
@Override
protected void doResolve(String inetHost, Promise<InetAddress> promise) throws Exception {
try {
promise.setSuccess(InetAddress.getByName(inetHost));
promise.setSuccess(SocketUtils.addressByName(inetHost));
} catch (UnknownHostException e) {
promise.setFailure(e);
}
@ -46,7 +47,7 @@ public class DefaultNameResolver extends InetNameResolver {
@Override
protected void doResolveAll(String inetHost, Promise<List<InetAddress>> promise) throws Exception {
try {
promise.setSuccess(Arrays.asList(InetAddress.getAllByName(inetHost)));
promise.setSuccess(Arrays.asList(SocketUtils.allAddressesByName(inetHost)));
} catch (UnknownHostException e) {
promise.setFailure(e);
}

View File

@ -25,6 +25,7 @@ import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.oio.OioDatagramChannel;
import io.netty.util.NetUtil;
import io.netty.util.internal.SocketUtils;
import org.junit.Test;
import java.net.InetSocketAddress;
@ -69,7 +70,7 @@ public class DatagramMulticastTest extends AbstractDatagramTest {
DatagramChannel cc = (DatagramChannel) cb.bind().sync().channel();
String group = "230.0.0.1";
InetSocketAddress groupAddress = new InetSocketAddress(group, addr.getPort());
InetSocketAddress groupAddress = SocketUtils.socketAddress(group, addr.getPort());
cc.joinGroup(groupAddress, NetUtil.LOOPBACK_IF).sync();

View File

@ -21,6 +21,7 @@ import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption;
import io.netty.util.internal.SocketUtils;
import org.junit.Ignore;
import org.junit.Test;
@ -57,7 +58,7 @@ public class ServerSocketSuspendTest extends AbstractServerSocketTest {
long startTime = System.nanoTime();
for (int i = 0; i < NUM_CHANNELS; i ++) {
Socket s = new Socket();
s.connect(addr, 10000);
SocketUtils.connect(s, addr, 10000);
sockets.add(s);
}

View File

@ -22,6 +22,7 @@ import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption;
import io.netty.util.internal.SocketUtils;
import io.netty.testsuite.util.TestUtils;
import io.netty.util.NetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
@ -33,7 +34,6 @@ import org.junit.Test;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import static org.hamcrest.CoreMatchers.*;
@ -108,7 +108,7 @@ public class SocketConnectionAttemptTest extends AbstractClientSocketTest {
boolean badHostTimedOut = true;
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(BAD_HOST, BAD_PORT), 10);
SocketUtils.connect(socket, SocketUtils.socketAddress(BAD_HOST, BAD_PORT), 10);
} catch (ConnectException e) {
badHostTimedOut = false;
// is thrown for no route to host when using Socket connect

View File

@ -20,6 +20,7 @@ import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.internal.SocketUtils;
import io.netty.channel.socket.ChannelInputShutdownEvent;
import io.netty.channel.socket.SocketChannel;
import org.junit.Test;
@ -45,7 +46,7 @@ public class SocketShutdownOutputByPeerTest extends AbstractServerSocketTest {
try {
sb.childHandler(h).childOption(ChannelOption.ALLOW_HALF_CLOSURE, true).bind().sync();
s.connect(addr, 10000);
SocketUtils.connect(s, addr, 10000);
s.getOutputStream().write(1);
assertEquals(1, (int) h.queue.take());
@ -82,7 +83,7 @@ public class SocketShutdownOutputByPeerTest extends AbstractServerSocketTest {
try {
sb.childHandler(h).bind().sync();
s.connect(addr, 10000);
SocketUtils.connect(s, addr, 10000);
s.getOutputStream().write(1);
assertEquals(1, (int) h.queue.take());

View File

@ -21,6 +21,7 @@ import com.barchart.udt.nio.SocketChannelUDT;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.util.internal.SocketUtils;
import io.netty.channel.nio.AbstractNioMessageChannel;
import io.netty.channel.udt.DefaultUdtServerChannelConfig;
import io.netty.channel.udt.UdtChannel;
@ -121,8 +122,9 @@ public abstract class NioUdtAcceptorChannel extends AbstractNioMessageChannel im
@Override
protected SocketAddress localAddress0() {
return javaChannel().socket().getLocalSocketAddress();
return SocketUtils.localSocketAddress(javaChannel().socket());
}
@Override
public InetSocketAddress localAddress() {
return (InetSocketAddress) super.localAddress();
@ -145,7 +147,7 @@ public abstract class NioUdtAcceptorChannel extends AbstractNioMessageChannel im
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
final SocketChannelUDT channelUDT = javaChannel().accept();
final SocketChannelUDT channelUDT = (SocketChannelUDT) SocketUtils.accept(javaChannel());
if (channelUDT == null) {
return 0;
} else {

View File

@ -27,11 +27,16 @@ import io.netty.channel.nio.AbstractNioByteChannel;
import io.netty.channel.udt.DefaultUdtChannelConfig;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.UdtChannelConfig;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import static java.nio.channels.SelectionKey.OP_CONNECT;
@ -89,7 +94,7 @@ public class NioUdtByteConnectorChannel extends AbstractNioByteChannel implement
@Override
protected void doBind(final SocketAddress localAddress) throws Exception {
javaChannel().bind(localAddress);
privilegedBind(javaChannel(), localAddress);
}
@Override
@ -99,11 +104,11 @@ public class NioUdtByteConnectorChannel extends AbstractNioByteChannel implement
@Override
protected boolean doConnect(final SocketAddress remoteAddress,
final SocketAddress localAddress) throws Exception {
final SocketAddress localAddress) throws Exception {
doBind(localAddress != null? localAddress : new InetSocketAddress(0));
boolean success = false;
try {
final boolean connected = javaChannel().connect(remoteAddress);
final boolean connected = SocketUtils.connect(javaChannel(), remoteAddress);
if (!connected) {
selectionKey().interestOps(
selectionKey().interestOps() | OP_CONNECT);
@ -186,4 +191,20 @@ public class NioUdtByteConnectorChannel extends AbstractNioByteChannel implement
public InetSocketAddress remoteAddress() {
return (InetSocketAddress) super.remoteAddress();
}
private static void privilegedBind(final SocketChannelUDT socketChannel, final SocketAddress localAddress)
throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
socketChannel.bind(localAddress);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
}

View File

@ -22,6 +22,7 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.util.internal.SocketUtils;
import io.netty.channel.nio.AbstractNioMessageChannel;
import io.netty.channel.udt.DefaultUdtChannelConfig;
import io.netty.channel.udt.UdtChannel;
@ -94,7 +95,7 @@ public class NioUdtMessageConnectorChannel extends AbstractNioMessageChannel imp
@Override
protected void doBind(final SocketAddress localAddress) throws Exception {
javaChannel().bind(localAddress);
SocketUtils.bind(javaChannel(), localAddress);
}
@Override
@ -108,7 +109,7 @@ public class NioUdtMessageConnectorChannel extends AbstractNioMessageChannel imp
doBind(localAddress != null? localAddress : new InetSocketAddress(0));
boolean success = false;
try {
final boolean connected = javaChannel().connect(remoteAddress);
final boolean connected = SocketUtils.connect(javaChannel(), remoteAddress);
if (!connected) {
selectionKey().interestOps(
selectionKey().interestOps() | OP_CONNECT);

View File

@ -18,6 +18,7 @@ package io.netty.test.udt.util;
import com.barchart.udt.SocketUDT;
import com.barchart.udt.StatusUDT;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.ThreadLocalRandom;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
@ -106,7 +107,7 @@ public final class UnitHelp {
final String host) {
ServerSocket socket = null;
try {
final InetAddress address = InetAddress.getByName(host);
final InetAddress address = SocketUtils.addressByName(host);
socket = new ServerSocket(0, 3, address);
return (InetSocketAddress) socket.getLocalSocketAddress();
} catch (final Exception e) {

View File

@ -26,6 +26,7 @@ import io.netty.channel.DefaultChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ReflectiveChannelFactory;
import io.netty.util.internal.SocketUtils;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.GlobalEventExecutor;
@ -150,7 +151,7 @@ public abstract class AbstractBootstrap<B extends AbstractBootstrap<B, C>, C ext
* @see {@link #localAddress(SocketAddress)}
*/
public B localAddress(String inetHost, int inetPort) {
return localAddress(new InetSocketAddress(inetHost, inetPort));
return localAddress(SocketUtils.socketAddress(inetHost, inetPort));
}
/**
@ -257,7 +258,7 @@ public abstract class AbstractBootstrap<B extends AbstractBootstrap<B, C>, C ext
* Create a new {@link Channel} and bind it.
*/
public ChannelFuture bind(String inetHost, int inetPort) {
return bind(new InetSocketAddress(inetHost, inetPort));
return bind(SocketUtils.socketAddress(inetHost, inetPort));
}
/**

View File

@ -30,6 +30,7 @@ import io.netty.channel.nio.AbstractNioMessageChannel;
import io.netty.channel.socket.DatagramChannelConfig;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.InternetProtocolFamily;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
@ -193,7 +194,7 @@ public final class NioDatagramChannel
private void doBind0(SocketAddress localAddress) throws Exception {
if (PlatformDependent.javaVersion() >= 7) {
javaChannel().bind(localAddress);
SocketUtils.bind(javaChannel(), localAddress);
} else {
javaChannel().socket().bind(localAddress);
}

View File

@ -19,6 +19,7 @@ import io.netty.channel.ChannelException;
import io.netty.channel.socket.DatagramChannelConfig;
import io.netty.channel.socket.DefaultDatagramChannelConfig;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SocketUtils;
import java.lang.reflect.Method;
import java.net.InetAddress;
@ -132,7 +133,7 @@ class NioDatagramChannelConfig extends DefaultDatagramChannelConfig {
if (inf == null) {
return null;
} else {
Enumeration<InetAddress> addresses = inf.getInetAddresses();
Enumeration<InetAddress> addresses = SocketUtils.addressesFromNetworkInterface(inf);
if (addresses.hasMoreElements()) {
return addresses.nextElement();
}

View File

@ -18,6 +18,7 @@ package io.netty.channel.socket.nio;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.util.internal.SocketUtils;
import io.netty.channel.nio.AbstractNioMessageChannel;
import io.netty.channel.socket.DefaultServerSocketChannelConfig;
import io.netty.channel.socket.ServerSocketChannelConfig;
@ -118,7 +119,7 @@ public class NioServerSocketChannel extends AbstractNioMessageChannel
@Override
protected SocketAddress localAddress0() {
return javaChannel().socket().getLocalSocketAddress();
return SocketUtils.localSocketAddress(javaChannel().socket());
}
@Override
@ -137,7 +138,7 @@ public class NioServerSocketChannel extends AbstractNioMessageChannel
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
SocketChannel ch = javaChannel().accept();
SocketChannel ch = SocketUtils.accept(javaChannel());
try {
if (ch != null) {
@ -189,7 +190,7 @@ public class NioServerSocketChannel extends AbstractNioMessageChannel
throw new UnsupportedOperationException();
}
private final class NioServerSocketChannelConfig extends DefaultServerSocketChannelConfig {
private final class NioServerSocketChannelConfig extends DefaultServerSocketChannelConfig {
private NioServerSocketChannelConfig(NioServerSocketChannel channel, ServerSocket javaSocket) {
super(channel, javaSocket);
}

View File

@ -24,6 +24,7 @@ import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.channel.FileRegion;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.util.internal.SocketUtils;
import io.netty.channel.nio.AbstractNioByteChannel;
import io.netty.channel.socket.DefaultSocketChannelConfig;
import io.netty.channel.socket.ServerSocketChannel;
@ -314,9 +315,9 @@ public class NioSocketChannel extends AbstractNioByteChannel implements io.netty
private void doBind0(SocketAddress localAddress) throws Exception {
if (PlatformDependent.javaVersion() >= 7) {
javaChannel().bind(localAddress);
SocketUtils.bind(javaChannel(), localAddress);
} else {
javaChannel().socket().bind(localAddress);
SocketUtils.bind(javaChannel().socket(), localAddress);
}
}
@ -328,7 +329,7 @@ public class NioSocketChannel extends AbstractNioByteChannel implements io.netty
boolean success = false;
try {
boolean connected = javaChannel().connect(remoteAddress);
boolean connected = SocketUtils.connect(javaChannel(), remoteAddress);
if (!connected) {
selectionKey().interestOps(SelectionKey.OP_CONNECT);
}

View File

@ -20,6 +20,7 @@ import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.oio.AbstractOioMessageChannel;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
@ -131,7 +132,7 @@ public class OioServerSocketChannel extends AbstractOioMessageChannel
@Override
protected SocketAddress localAddress0() {
return socket.getLocalSocketAddress();
return SocketUtils.localSocketAddress(socket);
}
@Override

View File

@ -25,6 +25,7 @@ import io.netty.channel.EventLoop;
import io.netty.channel.oio.OioByteStreamChannel;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
@ -267,19 +268,19 @@ public class OioSocketChannel extends OioByteStreamChannel implements SocketChan
@Override
protected void doBind(SocketAddress localAddress) throws Exception {
socket.bind(localAddress);
SocketUtils.bind(socket, localAddress);
}
@Override
protected void doConnect(SocketAddress remoteAddress,
SocketAddress localAddress) throws Exception {
if (localAddress != null) {
socket.bind(localAddress);
SocketUtils.bind(socket, localAddress);
}
boolean success = false;
try {
socket.connect(remoteAddress, config().getConnectTimeoutMillis());
SocketUtils.connect(socket, remoteAddress, config().getConnectTimeoutMillis());
activate(socket.getInputStream(), socket.getOutputStream());
success = true;
} catch (SocketTimeoutException e) {