Modified: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl.java?view=diff&rev=440907&r1=440906&r2=440907
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl.java Wed Sep 6 17:01:16 2006
@@ -43,399 +43,282 @@
*/
class PlainSocketImpl extends SocketImpl {
- // Const copy from socket
+ // Const copy from socket
- static final int MULTICAST_IF = 1;
+ static final int MULTICAST_IF = 1;
- static final int MULTICAST_TTL = 2;
+ static final int MULTICAST_TTL = 2;
- static final int TCP_NODELAY = 4;
+ static final int TCP_NODELAY = 4;
- static final int FLAG_SHUTDOWN = 8;
-
- // For SOCKS support. A SOCKS bind() uses the last
- // host connected to in its request.
- static private InetAddress lastConnectedAddress;
-
- static private int lastConnectedPort;
-
- private boolean tcpNoDelay = true;
-
- // used to store the trafficClass value which is simply returned
- // as the value that was set. We also need it to pass it to methods
- // that specify an address packets are going to be sent to
- private int trafficClass = 0;
-
- protected INetworkSystem netImpl = Platform.getNetworkSystem();
-
- public int receiveTimeout = 0;
-
- public boolean streaming = true;
-
- public boolean shutdownInput = false;
-
- Proxy proxy = null;
-
- private static Field fdField = null;
-
- private static Field localportField = null;
-
- /**
- * Accepts a connection on the provided socket, by calling the IP stack.
- *
- * @param newImpl
- * the socket to accept connections on
- * @exception SocketException
- * if an error occurs while accepting
- */
- protected void accept(SocketImpl newImpl) throws IOException {
- if (NetUtil.usingSocks(proxy)) {
- ((PlainSocketImpl) newImpl).socksBind();
- ((PlainSocketImpl) newImpl).socksAccept();
- return;
- }
-
- try {
- if (newImpl instanceof PlainSocketImpl) {
- PlainSocketImpl newPlainSocketImpl = (PlainSocketImpl) newImpl;
- netImpl.acceptStreamSocket(fd, newImpl, newPlainSocketImpl
- .getFileDescriptor(), receiveTimeout);
- newPlainSocketImpl.setLocalport(getLocalPort());
- } else {
- // if newImpl is not an instance of PlainSocketImpl, use
- // reflection to get/set protected fields.
- if (null == fdField) {
- fdField = getSocketImplField("fd"); // $NON-NLS-1$
- }
- FileDescriptor newFd = (FileDescriptor) fdField.get(newImpl);
- netImpl.acceptStreamSocket(fd, newImpl, newFd, receiveTimeout);
-
- if (null == localportField) {
- localportField = getSocketImplField("localport"); // $NON-NLS-1$
- }
- localportField.setInt(newImpl, getLocalPort());
- }
- } catch (InterruptedIOException e) {
- throw new SocketTimeoutException(e.getMessage());
- } catch (IllegalAccessException e) {
- // empty
- }
- }
-
- /*
- * gets SocketImpl field by reflection.
- */
- private Field getSocketImplField(final String fieldName) {
- return AccessController.doPrivileged(new PrivilegedAction<Field>() {
- public Field run() {
- Field field = null;
- try {
- field = SocketImpl.class.getDeclaredField(fieldName); //$NON-NLS-1$
- field.setAccessible(true);
- } catch (NoSuchFieldException e) {
- throw new Error(e);
- }
- return field;
- }
- });
- }
-
- /**
- * Answer the number of bytes that may be read from this socket without
- * blocking. This call does not block.
- *
- * @return int the number of bytes that may be read without blocking
- * @exception SocketException
- * if an error occurs while peeking
- */
-
- protected synchronized int available() throws IOException {
- // we need to check if the input has been shutdown. If so
- // we should return that there is no data to be read
- if (shutdownInput == true) {
- return 0;
- }
- return netImpl.availableStream(fd);
- }
-
- /**
- * Binds this socket to the specified local host/port. Binding to the 0 port
- * implies binding to any available port. By not making the assignment to
- * the instVar, the getLocalPort method will lazily go to the stack and
- * query for the assigned port
- *
- * @param anAddr
- * the local machine address to bind the socket to
- * @param aPort
- * the port on the local machine to bind the socket to
- * @exception IOException
- * if an error occurs while binding
- */
- protected void bind(InetAddress anAddr, int aPort) throws IOException {
- if (NetUtil.usingSocks(proxy)) {
- socksBind();
- return;
- }
- netImpl.bind(fd, aPort, anAddr);
- // PlainSocketImpl2.socketBindImpl2(fd, aPort, anAddr);
- address = anAddr;
- if (0 != aPort) {
- localport = aPort;
- } else {
- localport = netImpl.getSocketLocalPort(fd,
- NetUtil.preferIPv6Addresses());
- }
- }
-
- /**
- * Close the socket. Usage thereafter is invalid.
- *
- * @exception IOException
- * if an error occurs while closing
- */
- protected void close() throws IOException {
- synchronized (fd) {
- if (fd.valid()) {
- if ((netImpl.getSocketFlags() & FLAG_SHUTDOWN) != 0) {
- try {
- shutdownOutput();
- } catch (Exception e) {
- }
- }
- netImpl.socketClose(fd);
- fd = new FileDescriptor();
- }
- }
- }
-
- /**
- * Connects this socket to the specified remote host/port. This method
- * assumes the sender has verified the host with the security policy.
- *
- * @param aHost
- * the remote host to connect to
- * @param aPort
- * the remote port to connect to
- * @exception IOException
- * if an error occurs while connecting
- */
- protected void connect(String aHost, int aPort) throws IOException {
- // InetAddress anAddr = InetAddress.getHostByNameImpl(aHost,
- // preferIPv6Addresses());
- InetAddress anAddr = netImpl.getHostByName(aHost,
- NetUtil.preferIPv6Addresses());
- connect(anAddr, aPort);
- }
-
- /**
- * Connects this socket to the specified remote host address/port.
- *
- * @param anAddr
- * the remote host address to connect to
- * @param aPort
- * the remote port to connect to
- * @exception IOException
- * if an error occurs while connecting
- */
- protected void connect(InetAddress anAddr, int aPort) throws IOException {
- connect(anAddr, aPort, 0);
- }
-
- /**
- * Connects this socket to the specified remote host address/port.
- *
- * @param anAddr
- * the remote host address to connect to
- * @param aPort
- * the remote port to connect to
- * @param timeout
- * a timeout where supported. 0 means no timeout
- * @exception IOException
- * if an error occurs while connecting
- */
- private void connect(InetAddress anAddr, int aPort, int timeout)
- throws IOException {
- InetAddress address = anAddr.isAnyLocalAddress() ? InetAddress
- .getByName("localhost") : anAddr;
-
- try {
- if (streaming) {
- if (NetUtil.usingSocks(proxy)) {
- socksConnect(anAddr, aPort, 0);
- } else {
- if (timeout == 0) {
- // PlainSocketImpl2.connectStreamSocketImpl2(fd, aPort,
- // trafficClass, address);
- netImpl.connect(fd, trafficClass, address, aPort);
- } else {
- // PlainSocketImpl2.connectStreamWithTimeoutSocketImpl2(
- // fd, aPort, timeout, trafficClass, address);
- netImpl.connectStreamWithTimeoutSocket(fd, aPort,
- timeout, trafficClass, address);
- }
- }
- }
- } catch (ConnectException e) {
- throw new ConnectException(anAddr + ":" + aPort + " - "
- + e.getMessage());
- }
- super.address = anAddr;
- super.port = aPort;
- }
-
- /**
- * Creates a new unconnected socket. If streaming is true, create a stream
- * socket, else a datagram socket. The deprecated datagram usage is not
- * supported and will throw an exception.
- *
- * @param streaming
- * true, if the socket is type streaming
- * @exception SocketException
- * if an error occurs while creating the socket
- */
- protected void create(boolean streaming) throws IOException {
- this.streaming = streaming;
- // if (streaming) {
- // createStreamSocketImpl(fd, Socket.preferIPv4Stack());
- // } else {
- // createDatagramSocketImpl(fd, Socket.preferIPv4Stack());
- // }
-
- if (streaming) {
- netImpl.createStreamSocket(fd, NetUtil.preferIPv4Stack());
- } else {
- netImpl.createDatagramSocket(fd, NetUtil.preferIPv4Stack());
- }
- }
-
- protected void finalize() throws IOException {
- close();
- }
-
- /**
- * Answer the socket input stream.
- *
- * @return InputStream an InputStream on the socket
- * @exception IOException
- * thrown if an error occurs while accessing the stream
- */
- protected synchronized InputStream getInputStream() throws IOException {
- if (!fd.valid()) {
- throw new SocketException(Msg.getString("K003d"));
- }
-
- return new SocketInputStream(this);
- }
-
- /**
- * Answer the nominated socket option. Receive timeouts are maintained in
- * Java, rather than in the JNI code.
- *
- * @param optID
- * the socket option to retrieve
- * @return Object the option value
- * @exception SocketException
- * thrown if an error occurs while accessing the option
- */
- public Object getOption(int optID) throws SocketException {
- if (optID == SocketOptions.SO_TIMEOUT) {
- return new Integer(receiveTimeout);
- } else if (optID == SocketOptions.IP_TOS) {
- return new Integer(trafficClass);
- } else {
- // Call the native first so there will be
- // an exception if the socket if closed.
- Object result = netImpl.getSocketOption(fd, optID);
- if (optID == SocketOptions.TCP_NODELAY
- && (netImpl.getSocketFlags() & TCP_NODELAY) != 0) {
- return new Boolean(tcpNoDelay);
- }
- return result;
- }
- }
-
- /**
- * Answer the socket output stream.
- *
- * @return OutputStream an OutputStream on the socket
- * @exception IOException
- * thrown if an error occurs while accessing the stream
- */
- protected synchronized OutputStream getOutputStream() throws IOException {
- if (!fd.valid()) {
- throw new SocketException(Msg.getString("K003d"));
- }
- return new SocketOutputStream(this);
- }
-
- /**
- * Listen for connection requests on this stream socket. Incoming connection
- * requests are queued, up to the limit nominated by backlog. Additional
- * requests are rejected. listen() may only be invoked on stream sockets.
- *
- * @param backlog
- * the max number of outstanding connection requests
- * @exception IOException
- * thrown if an error occurs while listening
- */
- protected void listen(int backlog) throws IOException {
- if (NetUtil.usingSocks(proxy)) {
- // Do nothing for a SOCKS connection. The listen occurs on the
- // server during the bind.
- return;
- }
- // listenStreamSocketImpl(fd, backlog);
- netImpl.listenStreamSocket(fd, backlog);
- }
-
- /**
- * Set the nominated socket option. Receive timeouts are maintained in Java,
- * rather than in the JNI code.
- *
- * @param optID
- * the socket option to set
- * @param val
- * the option value
- * @exception SocketException
- * thrown if an error occurs while setting the option
- */
- public void setOption(int optID, Object val) throws SocketException {
- if (optID == SocketOptions.SO_TIMEOUT) {
- receiveTimeout = ((Integer) val).intValue();
- } else {
- try {
- netImpl.setSocketOption(fd, optID, val);
- if (optID == SocketOptions.TCP_NODELAY
- && (netImpl.getSocketFlags() & TCP_NODELAY) != 0) {
- tcpNoDelay = ((Boolean) val).booleanValue();
- }
- } catch (SocketException e) {
-
- // we don't through an exception for IP_TOS even if the platform
- // won't let us set the requested value
- if (optID != SocketOptions.IP_TOS) {
- throw e;
- }
- }
-
- // save this value as it is acutally used differently for IPv4 and
- // IPv6 so we cannot get the value using the getOption. The option
- // is actually only set for IPv4 and a masked version of the value
- // will be set as only a subset of the values are allowed on the
- // socket. Therefore we need to retain it to return the value that
- // was set. We also need the value to be passed into a number of
- // natives so that it can be used properly with IPv6
- if (optID == SocketOptions.IP_TOS) {
- trafficClass = ((Integer) val).intValue();
- }
- }
- }
+ static final int FLAG_SHUTDOWN = 8;
+
+ // For SOCKS support. A SOCKS bind() uses the last
+ // host connected to in its request.
+ static private InetAddress lastConnectedAddress;
+
+ static private int lastConnectedPort;
+
+ private static Field fdField;
+
+ private static Field localportField;
+
+ private boolean tcpNoDelay = true;
+
+ /**
+ * used to store the trafficClass value which is simply returned as the
+ * value that was set. We also need it to pass it to methods that specify an
+ * address packets are going to be sent to
+ */
+ private int trafficClass;
+
+ protected INetworkSystem netImpl = Platform.getNetworkSystem();
+
+ public int receiveTimeout = 0;
+
+ public boolean streaming = true;
+
+ public boolean shutdownInput;
+
+ Proxy proxy;
+
+ @Override
+ protected void accept(SocketImpl newImpl) throws IOException {
+ if (NetUtil.usingSocks(proxy)) {
+ ((PlainSocketImpl) newImpl).socksBind();
+ ((PlainSocketImpl) newImpl).socksAccept();
+ return;
+ }
+
+ try {
+ if (newImpl instanceof PlainSocketImpl) {
+ PlainSocketImpl newPlainSocketImpl = (PlainSocketImpl) newImpl;
+ netImpl.acceptStreamSocket(fd, newImpl, newPlainSocketImpl.getFileDescriptor(),
+ receiveTimeout);
+ newPlainSocketImpl.setLocalport(getLocalPort());
+ } else {
+ // if newImpl is not an instance of PlainSocketImpl, use
+ // reflection to get/set protected fields.
+ if (null == fdField) {
+ fdField = getSocketImplField("fd"); // $NON-NLS-1$
+ }
+ FileDescriptor newFd = (FileDescriptor) fdField.get(newImpl);
+ netImpl.acceptStreamSocket(fd, newImpl, newFd, receiveTimeout);
+
+ if (null == localportField) {
+ localportField = getSocketImplField("localport"); // $NON-NLS-1$
+ }
+ localportField.setInt(newImpl, getLocalPort());
+ }
+ } catch (InterruptedIOException e) {
+ throw new SocketTimeoutException(e.getMessage());
+ } catch (IllegalAccessException e) {
+ // empty
+ }
+ }
+
+ /**
+ * gets SocketImpl field by reflection.
+ */
+ private Field getSocketImplField(final String fieldName) {
+ return AccessController.doPrivileged(new PrivilegedAction<Field>() {
+ public Field run() {
+ Field field = null;
+ try {
+ field = SocketImpl.class.getDeclaredField(fieldName);
+ field.setAccessible(true);
+ } catch (NoSuchFieldException e) {
+ throw new Error(e);
+ }
+ return field;
+ }
+ });
+ }
+
+ @Override
+ protected synchronized int available() throws IOException {
+ // we need to check if the input has been shutdown. If so
+ // we should return that there is no data to be read
+ if (shutdownInput == true) {
+ return 0;
+ }
+ return netImpl.availableStream(fd);
+ }
+
+ @Override
+ protected void bind(InetAddress anAddr, int aPort) throws IOException {
+ if (NetUtil.usingSocks(proxy)) {
+ socksBind();
+ return;
+ }
+ netImpl.bind(fd, aPort, anAddr);
+ // PlainSocketImpl2.socketBindImpl2(fd, aPort, anAddr);
+ address = anAddr;
+ if (0 != aPort) {
+ localport = aPort;
+ } else {
+ localport = netImpl.getSocketLocalPort(fd, NetUtil.preferIPv6Addresses());
+ }
+ }
+
+ @Override
+ protected void close() throws IOException {
+ synchronized (fd) {
+ if (fd.valid()) {
+ if ((netImpl.getSocketFlags() & FLAG_SHUTDOWN) != 0) {
+ try {
+ shutdownOutput();
+ } catch (Exception e) {
+ }
+ }
+ netImpl.socketClose(fd);
+ fd = new FileDescriptor();
+ }
+ }
+ }
+
+ @Override
+ protected void connect(String aHost, int aPort) throws IOException {
+ InetAddress anAddr = netImpl.getHostByName(aHost, NetUtil.preferIPv6Addresses());
+ connect(anAddr, aPort);
+ }
+
+ @Override
+ protected void connect(InetAddress anAddr, int aPort) throws IOException {
+ connect(anAddr, aPort, 0);
+ }
+
+ /**
+ * Connects this socket to the specified remote host address/port.
+ *
+ * @param anAddr the remote host address to connect to
+ * @param aPort the remote port to connect to
+ * @param timeout a timeout where supported. 0 means no timeout
+ * @throws IOException if an error occurs while connecting
+ */
+ private void connect(InetAddress anAddr, int aPort, int timeout) throws IOException {
+ InetAddress address = anAddr.isAnyLocalAddress() ? InetAddress.getByName("localhost")
+ : anAddr;
+
+ try {
+ if (streaming) {
+ if (NetUtil.usingSocks(proxy)) {
+ socksConnect(anAddr, aPort, 0);
+ } else {
+ if (timeout == 0) {
+ netImpl.connect(fd, trafficClass, address, aPort);
+ } else {
+ netImpl.connectStreamWithTimeoutSocket(fd, aPort, timeout,
+ trafficClass, address);
+ }
+ }
+ }
+ } catch (ConnectException e) {
+ throw new ConnectException(anAddr + ":" + aPort + " - " + e.getMessage());
+ }
+ super.address = anAddr;
+ super.port = aPort;
+ }
+
+ @Override
+ protected void create(boolean streaming) throws IOException {
+ this.streaming = streaming;
+ if (streaming) {
+ netImpl.createStreamSocket(fd, NetUtil.preferIPv4Stack());
+ } else {
+ netImpl.createDatagramSocket(fd, NetUtil.preferIPv4Stack());
+ }
+ }
+
+ @Override
+ protected void finalize() throws IOException {
+ close();
+ }
+
+ @Override
+ protected synchronized InputStream getInputStream() throws IOException {
+ if (!fd.valid()) {
+ throw new SocketException(Msg.getString("K003d"));
+ }
+
+ return new SocketInputStream(this);
+ }
+
+ @Override
+ public Object getOption(int optID) throws SocketException {
+ if (optID == SocketOptions.SO_TIMEOUT) {
+ return new Integer(receiveTimeout);
+ } else if (optID == SocketOptions.IP_TOS) {
+ return new Integer(trafficClass);
+ } else {
+ // Call the native first so there will be
+ // an exception if the socket if closed.
+ Object result = netImpl.getSocketOption(fd, optID);
+ if (optID == SocketOptions.TCP_NODELAY
+ && (netImpl.getSocketFlags() & TCP_NODELAY) != 0) {
+ return new Boolean(tcpNoDelay);
+ }
+ return result;
+ }
+ }
+
+ @Override
+ protected synchronized OutputStream getOutputStream() throws IOException {
+ if (!fd.valid()) {
+ throw new SocketException(Msg.getString("K003d"));
+ }
+ return new SocketOutputStream(this);
+ }
+
+ @Override
+ protected void listen(int backlog) throws IOException {
+ if (NetUtil.usingSocks(proxy)) {
+ // Do nothing for a SOCKS connection. The listen occurs on the
+ // server during the bind.
+ return;
+ }
+ netImpl.listenStreamSocket(fd, backlog);
+ }
+
+ @Override
+ public void setOption(int optID, Object val) throws SocketException {
+ if (optID == SocketOptions.SO_TIMEOUT) {
+ receiveTimeout = ((Integer) val).intValue();
+ } else {
+ try {
+ netImpl.setSocketOption(fd, optID, val);
+ if (optID == SocketOptions.TCP_NODELAY
+ && (netImpl.getSocketFlags() & TCP_NODELAY) != 0) {
+ tcpNoDelay = ((Boolean) val).booleanValue();
+ }
+ } catch (SocketException e) {
+ // we don't throw an exception for IP_TOS even if the platform
+ // won't let us set the requested value
+ if (optID != SocketOptions.IP_TOS) {
+ throw e;
+ }
+ }
+
+ /*
+ * save this value as it is actually used differently for IPv4 and
+ * IPv6 so we cannot get the value using the getOption. The option
+ * is actually only set for IPv4 and a masked version of the value
+ * will be set as only a subset of the values are allowed on the
+ * socket. Therefore we need to retain it to return the value that
+ * was set. We also need the value to be passed into a number of
+ * natives so that it can be used properly with IPv6
+ */
+ if (optID == SocketOptions.IP_TOS) {
+ trafficClass = ((Integer) val).intValue();
+ }
+ }
+ }
/**
* Gets the SOCKS proxy server port.
*/
private int socksGetServerPort() {
- // get socks server port from proxy. It is unneccessary to check
+ // get socks server port from proxy. It is unnecessary to check
// "socksProxyPort" property, since proxy setting should only be
// determined by ProxySelector.
InetSocketAddress addr = (InetSocketAddress) proxy.address();
@@ -448,7 +331,7 @@
*/
private InetAddress socksGetServerAddress() throws UnknownHostException {
String proxyName;
- // get socks server address from proxy. It is unneccessary to check
+ // get socks server address from proxy. It is unnecessary to check
// "socksProxyHost" property, since all proxy setting should be
// determined by ProxySelector.
InetSocketAddress addr = (InetSocketAddress) proxy.address();
@@ -457,148 +340,133 @@
proxyName = addr.getAddress().getHostAddress();
}
- InetAddress anAddr = netImpl.getHostByName(proxyName, NetUtil
- .preferIPv6Addresses());
+ InetAddress anAddr = netImpl.getHostByName(proxyName, NetUtil.preferIPv6Addresses());
return anAddr;
}
- /**
- * Connect using a SOCKS server.
- */
- private void socksConnect(InetAddress applicationServerAddress,
- int applicationServerPort, int timeout) throws IOException {
- try {
- if (timeout == 0) {
- // PlainSocketImpl2.connectStreamSocketImpl2(fd,
- // socksGetServerPort(), trafficClass,
- // socksGetServerAddress());
- netImpl.connect(fd, trafficClass, socksGetServerAddress(),
- socksGetServerPort());
- } else {
- // PlainSocketImpl2.connectStreamWithTimeoutSocketImpl2(fd,
- // socksGetServerPort(), timeout, trafficClass,
- // socksGetServerAddress());
- netImpl.connectStreamWithTimeoutSocket(fd,
- socksGetServerPort(), timeout, trafficClass,
- socksGetServerAddress());
- }
-
- } catch (Exception e) {
- throw new SocketException(Msg.getString("K003e", e));
- }
-
- socksRequestConnection(applicationServerAddress, applicationServerPort);
-
- lastConnectedAddress = applicationServerAddress;
- lastConnectedPort = applicationServerPort;
- }
-
- /**
- * Request a SOCKS connection to the application server given. If the
- * request fails to complete successfully, an exception is thrown.
- */
- private void socksRequestConnection(InetAddress applicationServerAddress,
- int applicationServerPort) throws IOException {
- socksSendRequest(Socks4Message.COMMAND_CONNECT,
- applicationServerAddress, applicationServerPort);
- Socks4Message reply = socksReadReply();
- if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
- throw new IOException(reply.getErrorString(reply
- .getCommandOrResult()));
- }
- }
-
- /**
- * Perform an accept for a SOCKS bind.
- */
- public void socksAccept() throws IOException {
- Socks4Message reply = socksReadReply();
- if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
- throw new IOException(reply.getErrorString(reply
- .getCommandOrResult()));
- }
- }
-
- /**
- * Shutdown the input portion of the socket.
- */
- protected void shutdownInput() throws IOException {
- shutdownInput = true;
- // shutdownInputImpl(fd);
- netImpl.shutdownInput(fd);
- }
-
- /**
- * Shutdown the output portion of the socket.
- */
- protected void shutdownOutput() throws IOException {
- // shutdownOutputImpl(fd);
- netImpl.shutdownOutput(fd);
- }
-
- /**
- * Bind using a SOCKS server.
- */
- private void socksBind() throws IOException {
- try {
- // PlainSocketImpl2.connectStreamSocketImpl2(fd,
- // socksGetServerPort(),
- // trafficClass, socksGetServerAddress());
- netImpl.connect(fd, trafficClass, socksGetServerAddress(),
- socksGetServerPort());
- } catch (Exception e) {
- throw new IOException(Msg.getString("K003f", e));
- }
-
- // There must be a connection to an application host for the bind to
- // work.
- if (lastConnectedAddress == null) {
- throw new SocketException(Msg.getString("K0040"));
- }
-
- // Use the last connected address and port in the bind request.
- socksSendRequest(Socks4Message.COMMAND_BIND, lastConnectedAddress,
- lastConnectedPort);
- Socks4Message reply = socksReadReply();
-
- if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
- throw new IOException(reply.getErrorString(reply
- .getCommandOrResult()));
- }
-
- // A peculiarity of socks 4 - if the address returned is 0, use the
- // original socks server address.
- if (reply.getIP() == 0) {
- address = socksGetServerAddress();
- } else {
- // IPv6 support not yet required as
- // currently the Socks4Message.getIP() only returns int,
- // so only works with IPv4 4byte addresses
- byte[] replyBytes = new byte[4];
- intToBytes(reply.getIP(), replyBytes, 0);
- address = InetAddress.getByAddress(replyBytes);
- }
- localport = reply.getPort();
- }
-
- /**
- * Send a SOCKS V4 request.
- */
- private void socksSendRequest(int command, InetAddress address, int port)
- throws IOException {
- Socks4Message request = new Socks4Message();
- request.setCommandOrResult(command);
- request.setPort(port);
- request.setIP(address.getAddress());
- request.setUserId("default");
-
- getOutputStream().write(request.getBytes(), 0, request.getLength());
- }
-
- /**
- * Read a SOCKS V4 reply.
- */
- private Socks4Message socksReadReply() throws IOException {
+ /**
+ * Connect using a SOCKS server.
+ */
+ private void socksConnect(InetAddress applicationServerAddress, int applicationServerPort,
+ int timeout) throws IOException {
+ try {
+ if (timeout == 0) {
+ netImpl
+ .connect(fd, trafficClass, socksGetServerAddress(),
+ socksGetServerPort());
+ } else {
+ netImpl.connectStreamWithTimeoutSocket(fd, socksGetServerPort(), timeout,
+ trafficClass, socksGetServerAddress());
+ }
+
+ } catch (Exception e) {
+ throw new SocketException(Msg.getString("K003e", e));
+ }
+
+ socksRequestConnection(applicationServerAddress, applicationServerPort);
+
+ lastConnectedAddress = applicationServerAddress;
+ lastConnectedPort = applicationServerPort;
+ }
+
+ /**
+ * Request a SOCKS connection to the application server given. If the
+ * request fails to complete successfully, an exception is thrown.
+ */
+ private void socksRequestConnection(InetAddress applicationServerAddress,
+ int applicationServerPort) throws IOException {
+ socksSendRequest(Socks4Message.COMMAND_CONNECT, applicationServerAddress,
+ applicationServerPort);
+ Socks4Message reply = socksReadReply();
+ if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
+ throw new IOException(reply.getErrorString(reply.getCommandOrResult()));
+ }
+ }
+
+ /**
+ * Perform an accept for a SOCKS bind.
+ */
+ public void socksAccept() throws IOException {
+ Socks4Message reply = socksReadReply();
+ if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
+ throw new IOException(reply.getErrorString(reply.getCommandOrResult()));
+ }
+ }
+
+ /**
+ * Shutdown the input portion of the socket.
+ */
+ @Override
+ protected void shutdownInput() throws IOException {
+ shutdownInput = true;
+ netImpl.shutdownInput(fd);
+ }
+
+ /**
+ * Shutdown the output portion of the socket.
+ */
+ @Override
+ protected void shutdownOutput() throws IOException {
+ netImpl.shutdownOutput(fd);
+ }
+
+ /**
+ * Bind using a SOCKS server.
+ */
+ private void socksBind() throws IOException {
+ try {
+ netImpl.connect(fd, trafficClass, socksGetServerAddress(), socksGetServerPort());
+ } catch (Exception e) {
+ throw new IOException(Msg.getString("K003f", e));
+ }
+
+ // There must be a connection to an application host for the bind to
+ // work.
+ if (lastConnectedAddress == null) {
+ throw new SocketException(Msg.getString("K0040"));
+ }
+
+ // Use the last connected address and port in the bind request.
+ socksSendRequest(Socks4Message.COMMAND_BIND, lastConnectedAddress, lastConnectedPort);
+ Socks4Message reply = socksReadReply();
+
+ if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
+ throw new IOException(reply.getErrorString(reply.getCommandOrResult()));
+ }
+
+ // A peculiarity of socks 4 - if the address returned is 0, use the
+ // original socks server address.
+ if (reply.getIP() == 0) {
+ address = socksGetServerAddress();
+ } else {
+ // IPv6 support not yet required as
+ // currently the Socks4Message.getIP() only returns int,
+ // so only works with IPv4 4byte addresses
+ byte[] replyBytes = new byte[4];
+ NetUtil.intToBytes(reply.getIP(), replyBytes, 0);
+ address = InetAddress.getByAddress(replyBytes);
+ }
+ localport = reply.getPort();
+ }
+
+ /**
+ * Send a SOCKS V4 request.
+ */
+ private void socksSendRequest(int command, InetAddress address, int port)
+ throws IOException {
+ Socks4Message request = new Socks4Message();
+ request.setCommandOrResult(command);
+ request.setPort(port);
+ request.setIP(address.getAddress());
+ request.setUserId("default");
+
+ getOutputStream().write(request.getBytes(), 0, request.getLength());
+ }
+
+ /**
+ * Read a SOCKS V4 reply.
+ */
+ private Socks4Message socksReadReply() throws IOException {
Socks4Message reply = new Socks4Message();
int bytesRead = 0;
while (bytesRead < Socks4Message.REPLY_LENGTH) {
@@ -615,92 +483,52 @@
return reply;
}
- /**
- * Connect the socket to the host/port specified by the SocketAddress with a
- * specified timeout.
- *
- *
- * @param remoteAddr
- * the remote machine address and port to connect to
- * @param timeout
- * the millisecond timeout value, the connect will block
- * indefinitely for a zero value.
- *
- * @exception IOException
- * if a problem occurs during the connect
- */
- protected void connect(SocketAddress remoteAddr, int timeout)
- throws IOException {
- InetSocketAddress inetAddr = (InetSocketAddress) remoteAddr;
- connect(inetAddr.getAddress(), inetAddr.getPort(), timeout);
- }
-
- /**
- * Answer if the socket supports urgent data.
- */
- protected boolean supportsUrgentData() {
- // return !streaming || SocketImpl.supportsUrgentDataImpl(fd);
- return !streaming || netImpl.supportsUrgentData(fd);
- }
-
- /**
- * Send the single byte of urgent data on the socket.
- *
- * @param value
- * the byte of urgent data
- *
- * @exception IOException
- * when an error occurs sending urgent data
- */
- protected void sendUrgentData(int value) throws IOException {
- // SocketImpl.sendUrgentDataImpl(fd, (byte) value);
- netImpl.sendUrgentData(fd, (byte) value);
- }
-
- FileDescriptor getFD() {
- return fd;
- }
-
- private void setLocalport(int localport) {
- this.localport = localport;
- }
-
- int read(byte[] buffer, int offset, int count) throws IOException {
- if (shutdownInput) {
- return -1;
- }
- try {
- // int read = receiveStreamImpl(fd, buffer, offset, count,
- // receiveTimeout);
- int read = netImpl.receiveStream(fd, buffer, offset, count,
- receiveTimeout);
- if (read == -1) {
- shutdownInput = true;
- }
- return read;
- } catch (InterruptedIOException e) {
- throw new SocketTimeoutException(e.getMessage());
- }
- }
-
- int write(byte[] buffer, int offset, int count) throws IOException {
- if (!streaming) {
- // PlainSocketImpl2.sendDatagramImpl2(fd, buffer, offset, count,
- // port,
- // address);
- netImpl
- .sendDatagram2(fd, buffer, offset, count, port, address);
- }
- // return sendStreamImpl(fd, buffer, offset, count);
- return netImpl.sendStream(fd, buffer, offset, count);
- }
-
- static void intToBytes(int value, byte bytes[], int start) {
- // Shift the int so the current byte is right-most
- // Use a byte mask of 255 to single out the last byte.
- bytes[start] = (byte) ((value >> 24) & 255);
- bytes[start + 1] = (byte) ((value >> 16) & 255);
- bytes[start + 2] = (byte) ((value >> 8) & 255);
- bytes[start + 3] = (byte) (value & 255);
- }
+ @Override
+ protected void connect(SocketAddress remoteAddr, int timeout) throws IOException {
+ InetSocketAddress inetAddr = (InetSocketAddress) remoteAddr;
+ connect(inetAddr.getAddress(), inetAddr.getPort(), timeout);
+ }
+
+ /**
+ * Answer if the socket supports urgent data.
+ */
+ @Override
+ protected boolean supportsUrgentData() {
+ return !streaming || netImpl.supportsUrgentData(fd);
+ }
+
+ @Override
+ protected void sendUrgentData(int value) throws IOException {
+ netImpl.sendUrgentData(fd, (byte) value);
+ }
+
+ FileDescriptor getFD() {
+ return fd;
+ }
+
+ private void setLocalport(int localport) {
+ this.localport = localport;
+ }
+
+ int read(byte[] buffer, int offset, int count) throws IOException {
+ if (shutdownInput) {
+ return -1;
+ }
+ try {
+ int read = netImpl.receiveStream(fd, buffer, offset, count, receiveTimeout);
+ if (read == -1) {
+ shutdownInput = true;
+ }
+ return read;
+ } catch (InterruptedIOException e) {
+ throw new SocketTimeoutException(e.getMessage());
+ }
+ }
+
+ int write(byte[] buffer, int offset, int count) throws IOException {
+ if (!streaming) {
+ netImpl.sendDatagram2(fd, buffer, offset, count, port, address);
+ }
+ return netImpl.sendStream(fd, buffer, offset, count);
+ }
}
Modified: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl2.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl2.java?view=diff&rev=440907&r1=440906&r2=440907
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl2.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl2.java Wed Sep 6 17:01:16 2006
@@ -19,8 +19,6 @@
import java.io.IOException;
import java.net.InetAddress;
import java.net.Proxy;
-import java.net.SocketException;
-
/**
* This class was added so we can create sockets without options that were
@@ -32,137 +30,33 @@
*/
class PlainSocketImpl2 extends PlainSocketImpl {
- public PlainSocketImpl2(FileDescriptor fd, int localport, InetAddress addr, int port) {
+ public PlainSocketImpl2(FileDescriptor fd, int localport, InetAddress addr, int port) {
super();
super.fd = fd;
super.localport = localport;
super.address = addr;
super.port = port;
}
-
- public PlainSocketImpl2(){
+
+ public PlainSocketImpl2() {
super();
}
-
- /*
+
+ /**
* creates an instance with specified proxy.
*/
- public PlainSocketImpl2(Proxy proxy){
- super();
- this.proxy = proxy;
+ public PlainSocketImpl2(Proxy proxy) {
+ super();
+ this.proxy = proxy;
}
- /**
- * Answer the result of attempting to create a stream socket in the IP
- * stack. This version does not set certain options which were required for
- * server sockets and which the initial vesrion ended up setting for both
- * socket and serverSockets as the same method was used to create a socket
- * for both. We have added a new method so that we can preserve the behavior
- * of earlier versions
- *
- * @param aFD
- * the socket FileDescriptor
- * @exception SocketException
- * if an error occurs while creating the socket
- */
- // static native void createStreamSocketImpl2(FileDescriptor aFD,
- // boolean preferIPv4Stack) throws SocketException;
- //
- // /**
- // * Connect the underlying socket to the nominated remotehost/port.
- // *
- // * @param aFD
- // * the socket FileDescriptor
- // * @param aport
- // * the remote machine port to connect to
- // * @param trafficClass
- // * the traffic class to be used when connecting
- // * @param inetAddress
- // * the address to connect to
- // * @exception SocketException
- // * if an error occurs while connecting
- // */
- // static native void connectStreamSocketImpl2(FileDescriptor aFD, int
- // aport,
- // int trafficClass, InetAddress inetAddress) throws IOException;
- //
- // /**
- // * Connect the underlying socket to the nominated remotehost/port.
- // *
- // * @param aFD
- // * the socket FileDescriptor
- // * @param aport
- // * the remote machine port to connect to
- // * @param timeout
- // * timeout after which SocketTimeoutException will be thrown
- // * @param trafficClass
- // * the traffic class to be used when connecting
- // * @param inetAddress
- // * the address to connect to
- // * @exception SocketException
- // * if an error occurs while connecting
- // * @exception SocketTimeoutException
- // * if a timeout occurs while trying to connect
- // */
- // static native void connectStreamWithTimeoutSocketImpl2(FileDescriptor
- // aFD,
- // int aport, int timeout, int trafficClass, InetAddress inetAddress)
- // throws IOException;
- /**
- * Creates a new unconnected socket. If streaming is true, create a stream
- * socket, else a datagram socket. The deprecated datagram usage is not
- * supported and will throw an exception.
- *
- * @param isStreaming
- * true, if the socket is type streaming
- * @exception SocketException
- * if an error occurs while creating the socket
- */
- protected void create(boolean isStreaming) throws IOException {
- streaming = isStreaming;
- if (isStreaming) {
- netImpl.createSocket(fd, NetUtil.preferIPv4Stack());
- } else {
- netImpl.createDatagramSocket(fd, NetUtil.preferIPv4Stack());
- }
- }
-
- /**
- * Send the <code>data</code> to the nominated target <code>address</code>
- * and <code>port</code>. These values are derived from the
- * DatagramPacket to reduce the field calls within JNI.
- *
- * @param fd
- * the socket FileDescriptor
- * @param data
- * the data buffer of the packet
- * @param length
- * the length of the data buffer in the packet
- * @param port
- * the target host port
- * @param inetAddress
- * the address to send the datagram on
- *
- * @exception IOException
- * upon an read error or timeout
- */
- // static native int sendDatagramImpl2(FileDescriptor fd, byte[] data,
- // int offset, int length, int port, InetAddress inetAddress)
- // throws IOException;
- //
- // /**
- // * Bind the socket to the port/localhost in the IP stack.
- // *
- // * @param aFD
- // * the socket descriptor
- // * @param port
- // * the option selector
- // * @param inetAddress
- // * the address to be used
- // *
- // * @throws SocketException
- // * if bind operation fails
- // */
- // static native void socketBindImpl2(FileDescriptor aFD, int port,
- // InetAddress inetAddress) throws SocketException;
+ @Override
+ protected void create(boolean isStreaming) throws IOException {
+ streaming = isStreaming;
+ if (isStreaming) {
+ netImpl.createSocket(fd, NetUtil.preferIPv4Stack());
+ } else {
+ netImpl.createDatagramSocket(fd, NetUtil.preferIPv4Stack());
+ }
+ }
}
Modified: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketImplProvider.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketImplProvider.java?view=diff&rev=440907&r1=440906&r2=440907
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketImplProvider.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketImplProvider.java Wed Sep 6 17:01:16 2006
@@ -20,36 +20,37 @@
import java.net.Proxy;
import java.net.SocketImpl;
-
public class SocketImplProvider {
-
- public static SocketImpl getSocketImpl(){
+
+ public static SocketImpl getSocketImpl() {
return new PlainSocketImpl2();
}
- /*
+
+ /**
* gets a SocketImpl with specified proxy.
*/
- public static SocketImpl getSocketImpl(Proxy proxy){
+ public static SocketImpl getSocketImpl(Proxy proxy) {
return new PlainSocketImpl2(proxy);
}
-
- public static SocketImpl getSocketImpl(FileDescriptor fd, int localport, InetAddress addr, int port){
+
+ public static SocketImpl getSocketImpl(FileDescriptor fd, int localport, InetAddress addr,
+ int port) {
return new PlainSocketImpl2(fd, localport, addr, port);
- }
-
- public static SocketImpl getServerSocketImpl(){
+ }
+
+ public static SocketImpl getServerSocketImpl() {
return new PlainServerSocketImpl();
}
- public static SocketImpl getServerSocketImpl(FileDescriptor fd){
+ public static SocketImpl getServerSocketImpl(FileDescriptor fd) {
return new PlainServerSocketImpl(fd);
- }
-
- public static DatagramSocketImpl getDatagramSocketImpl(){
+ }
+
+ public static DatagramSocketImpl getDatagramSocketImpl() {
return new PlainDatagramSocketImpl();
}
-
- public static DatagramSocketImpl getMulticastSocketImpl(){
+
+ public static DatagramSocketImpl getMulticastSocketImpl() {
return new PlainMulticastSocketImpl();
}
Modified: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketInputStream.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketInputStream.java?view=diff&rev=440907&r1=440906&r2=440907
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketInputStream.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketInputStream.java Wed Sep 6 17:01:16 2006
@@ -20,7 +20,6 @@
import java.net.Socket;
import java.net.SocketImpl;
-
import org.apache.harmony.luni.util.Msg;
/**
@@ -30,139 +29,64 @@
*/
class SocketInputStream extends InputStream {
- private static final String ERRCODE_OFFSETCOUNT_OUTOFBOUND = "K002f"; //$NON-NLS-1$
-
- private static final String ERRCODE_OFFSET_OUTOFBOUND = "K002e"; //$NON-NLS-1$
-
- private static final String ERRCODE_BUFFER_NULL = "K0047"; //$NON-NLS-1$
-
- PlainSocketImpl socket;
+ private final PlainSocketImpl socket;
- /**
- * Constructs a SocketInputStream for the <code>socket</code>. Read
- * operations are forwarded to the <code>socket</code>.
- *
- * @param socket
- * the socket to be read
- * @see Socket
- */
- public SocketInputStream(SocketImpl socket) {
- super();
- this.socket = (PlainSocketImpl) socket;
- }
-
- /**
- * Answer the number of bytes that may be read without blocking. Zero
- * indicates a read operation would block. This call itself does not block,
- * but may throw an IOException.
- *
- * @return int the number of bytes that may be read without blocking
- * @exception IOException
- * thrown if an error occurs during the test
- */
- public int available() throws IOException {
- return socket.available();
- }
-
- /**
- * Close the stream and the underlying socket.
- *
- * @exception IOException
- * thrown if an error occurs during the close
- */
- public void close() throws IOException {
- socket.close();
- super.close();
- }
-
- /**
- * Read a single byte from the socket, answering the value as an
- * <code>int</code>. This call may block indefinitely, depending upon
- * whether data is available and whether the read timeout option has been
- * set on the socket. A value of -1 indicates 'end-of-file'.
- *
- * @return int the value read
- * @exception IOException
- * thrown if an error occurs during the read
- */
- public int read() throws IOException {
- byte[] buffer = new byte[1];
- int result = socket.read(buffer, 0, 1);
- return (-1 == result) ? result : buffer[0] & 0xFF;
- }
-
- /**
- * Read a buffer.length number of bytes from the socket, into the
- * <code>buffer</code>. This call may block indefinitely, depending upon
- * whether data is available and whether the read timeout option has been
- * set on the socket. The number of bytes actually read is returned; a value
- * of -1 indicates 'end-of-file'.
- *
- * @param buffer
- * the buffer to read into
- * @return int the number of bytes actually read
- * @exception IOException
- * thrown if an error occurs during the read
- */
- public int read(byte[] buffer) throws IOException {
- return read(buffer, 0, buffer.length);
- }
-
- /**
- * Read a <code>count</code> number of bytes from the socket, into the
- * <code>buffer</code> at an <code>offset</code>. This call may block
- * indefinitely, depending upon whether data is available and whether the
- * read timeout option has been set on the socket. The number of bytes
- * actually read is returned; a value of -1 indicates 'end-of-file'.
- *
- * @param buffer
- * the buffer to read into
- * @param offset
- * the offset into the buffer to start filling
- * @param count
- * the maximum number of bytes to read
- * @return int the number of bytes actually read
- * @exception IOException,
- * ArrayIndexOutOfBoundsException thrown if the argument
- * bounds are incorrect or an error occurs during the read
- */
- public int read(byte[] buffer, int offset, int count) throws IOException {
- if (null == buffer) {
- throw new IOException(Msg.getString(ERRCODE_BUFFER_NULL));
- }
-
- if (0 == count) {
- return 0;
- }
-
- if (0 > offset || offset >= buffer.length) {
- throw new ArrayIndexOutOfBoundsException(Msg
- .getString(ERRCODE_OFFSET_OUTOFBOUND));
- }
- if (0 > count || offset + count > buffer.length) {
- throw new ArrayIndexOutOfBoundsException(Msg
- .getString(ERRCODE_OFFSETCOUNT_OUTOFBOUND));
- }
-
- return socket.read(buffer, offset, count);
- }
-
- /**
- * Skips <code>n</code> number of bytes in this InputStream. Subsequent
- * <code>read()</code>'s will not return these bytes unless
- * <code>reset()</code> is used. This method may perform multiple reads to
- * read <code>n</code> bytes. This implementation reads <code>n</code>
- * bytes into a temporary buffer.
- *
- * @param n
- * the number of bytes to skip.
- * @return the number of bytes actually skipped.
- *
- * @exception java.io.IOException
- * If the stream is already closed or another IOException
- * occurs.
- */
- public long skip(long n) throws IOException {
- return (0 == n) ? 0 : super.skip(n);
- }
+ /**
+ * Constructs a SocketInputStream for the <code>socket</code>. Read
+ * operations are forwarded to the <code>socket</code>.
+ *
+ * @param socket the socket to be read
+ * @see Socket
+ */
+ public SocketInputStream(SocketImpl socket) {
+ super();
+ this.socket = (PlainSocketImpl) socket;
+ }
+
+ @Override
+ public int available() throws IOException {
+ return socket.available();
+ }
+
+ @Override
+ public void close() throws IOException {
+ socket.close();
+ }
+
+ @Override
+ public int read() throws IOException {
+ byte[] buffer = new byte[1];
+ int result = socket.read(buffer, 0, 1);
+ return (-1 == result) ? result : buffer[0] & 0xFF;
+ }
+
+ @Override
+ public int read(byte[] buffer) throws IOException {
+ return read(buffer, 0, buffer.length);
+ }
+
+ @Override
+ public int read(byte[] buffer, int offset, int count) throws IOException {
+ if (null == buffer) {
+ throw new IOException(Msg.getString("K0047"));//$NON-NLS-1$
+ }
+
+ if (0 == count) {
+ return 0;
+ }
+
+ if (0 > offset || offset >= buffer.length) {
+ throw new ArrayIndexOutOfBoundsException(Msg.getString("K002e"));//$NON-NLS-1$
+ }
+ if (0 > count || offset + count > buffer.length) {
+ throw new ArrayIndexOutOfBoundsException(Msg.getString("K002f"));//$NON-NLS-1$
+ }
+
+ return socket.read(buffer, offset, count);
+ }
+
+ @Override
+ public long skip(long n) throws IOException {
+ return (0 == n) ? 0 : super.skip(n);
+ }
}
Modified: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketOutputStream.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketOutputStream.java?view=diff&rev=440907&r1=440906&r2=440907
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketOutputStream.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/SocketOutputStream.java Wed Sep 6 17:01:16 2006
@@ -20,96 +20,54 @@
import java.net.Socket;
import java.net.SocketImpl;
+import org.apache.harmony.luni.util.Msg;
class SocketOutputStream extends OutputStream {
- private static final String ERRCODE_BUFFER_NULL = "K0047"; //$NON-NLS-1$
+ private PlainSocketImpl socket;
- private static final String ERRCODE_OFFSET_OUTOFBOUND = "K002f"; //$NON-NLS-1$
+ /**
+ * Constructs a SocketOutputStream for the <code>socket</code>. Write
+ * operations are forwarded to the <code>socket</code>.
+ *
+ * @param socket the socket to be written
+ * @see Socket
+ */
+ public SocketOutputStream(SocketImpl socket) {
+ super();
+ this.socket = (PlainSocketImpl) socket;
+ }
+
+ @Override
+ public void close() throws IOException {
+ socket.close();
+ }
+
+ @Override
+ public void write(byte[] buffer) throws IOException {
+ socket.write(buffer, 0, buffer.length);
+ }
+
+ @Override
+ public void write(byte[] buffer, int offset, int count) throws IOException {
+ // avoid int overflow
+ if (buffer != null) {
+ if (0 <= offset && offset <= buffer.length && 0 <= count
+ && count <= buffer.length - offset) {
+ socket.write(buffer, offset, count);
+ } else {
+ throw new ArrayIndexOutOfBoundsException(Msg.getString("K002f"));//$NON-NLS-1$
+ }
+ } else {
+ throw new NullPointerException(Msg.getString("K0047"));//$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public void write(int oneByte) throws IOException {
+ byte[] buffer = new byte[1];
+ buffer[0] = (byte) (oneByte & 0xFF);
- PlainSocketImpl socket;
-
- /**
- * Constructs a SocketOutputStream for the <code>socket</code>. Write
- * operations are forwarded to the <code>socket</code>.
- *
- * @param socket
- * the socket to be written
- * @see Socket
- */
-
- public SocketOutputStream(SocketImpl socket) {
- super();
- this.socket = (PlainSocketImpl) socket;
- }
-
- /**
- * Close the stream and the underlying socket.
- *
- * @exception IOException
- * thrown if an error occurs during the close
- */
-
- public void close() throws IOException {
- socket.close();
- super.close();
- }
-
- /**
- * Write the <code>buffer</code> to the socket.
- *
- * @param buffer
- * the buffer to write
- * @exception IOException
- * thrown if an error occurs during the write
- */
- public void write(byte[] buffer) throws IOException {
- socket.write(buffer, 0, buffer.length);
- }
-
- /**
- * Write the <code>count</code> number of bytes from the
- * <code>buffer</code> to the socket, starting at <code>offset</code>.
- *
- * @param buffer
- * the buffer to write
- * @param offset
- * the offset in buffer to start writing
- * @param count
- * the number of bytes to write
- * @exception IOException,
- * IndexOutOfBoundsException thrown if an error occurs during
- * the write
- */
- public void write(byte[] buffer, int offset, int count) throws IOException {
- // avoid int overflow
- if (buffer != null) {
- if (0 <= offset && offset <= buffer.length && 0 <= count
- && count <= buffer.length - offset) {
- socket.write(buffer, offset, count);
- } else {
- throw new ArrayIndexOutOfBoundsException(org.apache.harmony.luni.util.Msg
- .getString(ERRCODE_OFFSET_OUTOFBOUND));
- }
- } else {
- throw new NullPointerException(org.apache.harmony.luni.util.Msg
- .getString(ERRCODE_BUFFER_NULL));
- }
- }
-
- /**
- * Write a single byte, the lowest-order byte from an <code>int</code> to
- * the socket.
- *
- * @param oneByte
- * the value to write
- * @exception IOException
- * thrown if an error occurs during the write
- */
- public void write(int oneByte) throws IOException {
- byte[] buffer = new byte[1];
- buffer[0] = (byte) (oneByte & 0xFF);
-
- socket.write(buffer, 0, 1);
- }
+ socket.write(buffer, 0, 1);
+ }
}
Modified: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/Socks4Message.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/Socks4Message.java?view=diff&rev=440907&r1=440906&r2=440907
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/Socks4Message.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/main/java/org/apache/harmony/luni/net/Socks4Message.java Wed Sep 6 17:01:16 2006
@@ -18,234 +18,232 @@
import java.io.UnsupportedEncodingException;
class Socks4Message {
- protected byte[] buffer;
+ static final int COMMAND_CONNECT = 1;
- final static private int SOCKS_VERSION = 4;
+ static final int COMMAND_BIND = 2;
- final static public int COMMAND_CONNECT = 1;
+ static final int RETURN_SUCCESS = 90;
- final static public int COMMAND_BIND = 2;
+ static final int RETURN_FAILURE = 91;
- final static public int RETURN_SUCCESS = 90;
-
- final static public int RETURN_FAILURE = 91;
-
- final static public int RETURN_CANNOT_CONNECT_TO_IDENTD = 92;
-
- final static public int RETURN_DIFFERENT_USER_IDS = 93;
-
- final static protected int INDEX_VERSION = 0;
-
- final static private int INDEX_COMMAND = 1;
-
- final static private int INDEX_PORT = 2;
-
- final static private int INDEX_IP = 4;
-
- final static private int INDEX_USER_ID = 8;
-
- final static private int BUFFER_LENGTH = 256;
-
- final static public int REPLY_LENGTH = 8;
-
- final static private int MAX_USER_ID_LENGTH = BUFFER_LENGTH - INDEX_USER_ID;
-
- public Socks4Message() {
- super();
- buffer = new byte[BUFFER_LENGTH];
- setVersionNumber(SOCKS_VERSION);
- }
-
- /**
- * Get the request's command or result.
- */
- public int getCommandOrResult() {
- return buffer[INDEX_COMMAND];
- }
-
- /**
- * Set the request's command or result.
- */
- public void setCommandOrResult(int command) {
- buffer[INDEX_COMMAND] = (byte) command;
- }
-
- /**
- * Answer the request's port number.
- */
- public int getPort() {
- return getInt16(INDEX_PORT);
- }
-
- /**
- * Set the request's port number.
- */
- public void setPort(int port) {
- setInt16(INDEX_PORT, port);
- }
-
- /*
- * Answer the IP address of the request as an integer.
- */
- public int getIP() {
- return getInt32(INDEX_IP);
- }
-
- /**
- * Set the IP address. This expects an array of four bytes in host order.
- */
- public void setIP(byte[] ip) {
- buffer[INDEX_IP] = ip[0];
- buffer[INDEX_IP + 1] = ip[1];
- buffer[INDEX_IP + 2] = ip[2];
- buffer[INDEX_IP + 3] = ip[3];
- }
-
- /**
- * Answer the user id for authentication.
- */
- public String getUserId() {
- return getString(INDEX_USER_ID, MAX_USER_ID_LENGTH);
- }
-
- /**
- * Set the user id for authentication.
- */
- public void setUserId(String id) {
- setString(INDEX_USER_ID, MAX_USER_ID_LENGTH, id);
- }
-
- /**
- */
- public String toString() {
- StringBuffer buf = new StringBuffer("");
- buf.append("Version: ");
- buf.append(Integer.toHexString(getVersionNumber()));
- buf.append(" Command: ");
- buf.append(Integer.toHexString(getCommandOrResult()));
- buf.append(" Port: ");
- buf.append(getPort());
- buf.append(" IP: ");
- buf.append(Integer.toHexString(getIP()));
- buf.append(" User ID: ");
- buf.append(getUserId());
- return buf.toString();
- }
-
- /**
- * Answer the total number of bytes used for the request. This method
- * searches for the end of the user id, then searches for the end of the
- * password and returns the final index as the requests length.
- */
- public int getLength() {
- int index = 0;
-
- // Look for the end of the user id.
- for (index = INDEX_USER_ID; buffer[index] != 0; index++) {
- /*
- * Finds the end of the user id by searching for the null
- * termination of the user id string.
- */
- }
-
- // Increment the index to include the NULL character in the length;
- index++;
- return index;
- }
-
- /**
- * Answer an error string corresponding to the given error value.
- */
- public String getErrorString(int error) {
- switch (error) {
- case RETURN_FAILURE:
- return org.apache.harmony.luni.util.Msg.getString("K00cd");
- case RETURN_CANNOT_CONNECT_TO_IDENTD:
- return org.apache.harmony.luni.util.Msg.getString("K00ce");
- case RETURN_DIFFERENT_USER_IDS:
- return org.apache.harmony.luni.util.Msg.getString("K00cf");
- default:
- return org.apache.harmony.luni.util.Msg.getString("K00d0");
- }
- }
-
- /**
- * Answer the message's byte buffer.
- */
- public byte[] getBytes() {
- return buffer;
- }
-
- /**
- * Get a 16 bit integer from the buffer at the offset given.
- */
- private int getInt16(int offset) {
- return (((buffer[offset] & 0xFF) << 8) + (buffer[offset + 1] & 0xFF));
- }
-
- /**
- * Get a 32 bit integer from the buffer at the offset given.
- */
- private int getInt32(int offset) {
- return ((buffer[offset + 3] & 0xFF)
- + ((buffer[offset + 2] & 0xFF) << 8)
- + ((buffer[offset + 1] & 0xFF) << 16) + ((buffer[offset + 0] & 0xFF) << 24));
- }
-
- /**
- * Get a String from the buffer at the offset given. The method reads until
- * it encounters a null value or reaches the maxLength given.
- */
- private String getString(int offset, int maxLength) {
- int index = offset;
- int lastIndex = index + maxLength;
- String result;
-
- while (index < lastIndex && (buffer[index] != 0)) {
- index++;
- }
- try {
- result = new String(buffer, offset, index - offset, "ISO8859_1");
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e.toString());
- }
- return result;
- }
-
- /**
- * Answer the SOCKS version number. Should always be 4.
- */
- private int getVersionNumber() {
- return buffer[INDEX_VERSION];
- }
-
- /**
- * Put a 16 bit integer into the buffer at the offset given.
- */
- private void setInt16(int offset, int value) {
- buffer[offset] = (byte) (value >>> 8 & 0xFF);
- buffer[offset + 1] = (byte) (value & 0xFF);
- }
-
- /**
- * Put a string into the buffer at the offset given.
- */
- private void setString(int offset, int maxLength, String theString) {
- byte[] stringBytes;
- try {
- stringBytes = theString.getBytes("ISO8859_1");
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e.toString());
- }
- int length = Math.min(stringBytes.length, maxLength);
- System.arraycopy(stringBytes, 0, buffer, offset, length);
- buffer[offset + length] = 0;
- }
-
- /**
- * Set the SOCKS version number. This should always be 4.
- */
- private void setVersionNumber(int number) {
- buffer[INDEX_VERSION] = (byte) number;
- }
+ static final int RETURN_CANNOT_CONNECT_TO_IDENTD = 92;
+
+ static final int RETURN_DIFFERENT_USER_IDS = 93;
+
+ static final int REPLY_LENGTH = 8;
+
+ static final int INDEX_VERSION = 0;
+
+ private static final int SOCKS_VERSION = 4;
+
+ private static final int INDEX_COMMAND = 1;
+
+ private static final int INDEX_PORT = 2;
+
+ private static final int INDEX_IP = 4;
+
+ private static final int INDEX_USER_ID = 8;
+
+ private static final int BUFFER_LENGTH = 256;
+
+ private static final int MAX_USER_ID_LENGTH = BUFFER_LENGTH - INDEX_USER_ID;
+
+ protected byte[] buffer;
+
+ public Socks4Message() {
+ super();
+ buffer = new byte[BUFFER_LENGTH];
+ setVersionNumber(SOCKS_VERSION);
+ }
+
+ /**
+ * Get the request's command or result.
+ */
+ public int getCommandOrResult() {
+ return buffer[INDEX_COMMAND];
+ }
+
+ /**
+ * Set the request's command or result.
+ */
+ public void setCommandOrResult(int command) {
+ buffer[INDEX_COMMAND] = (byte) command;
+ }
+
+ /**
+ * Answer the request's port number.
+ */
+ public int getPort() {
+ return getInt16(INDEX_PORT);
+ }
+
+ /**
+ * Set the request's port number.
+ */
+ public void setPort(int port) {
+ setInt16(INDEX_PORT, port);
+ }
+
+ /*
+ * Answer the IP address of the request as an integer.
+ */
+ public int getIP() {
+ return getInt32(INDEX_IP);
+ }
+
+ /**
+ * Set the IP address. This expects an array of four bytes in host order.
+ */
+ public void setIP(byte[] ip) {
+ buffer[INDEX_IP] = ip[0];
+ buffer[INDEX_IP + 1] = ip[1];
+ buffer[INDEX_IP + 2] = ip[2];
+ buffer[INDEX_IP + 3] = ip[3];
+ }
+
+ /**
+ * Answer the user id for authentication.
+ */
+ public String getUserId() {
+ return getString(INDEX_USER_ID, MAX_USER_ID_LENGTH);
+ }
+
+ /**
+ * Set the user id for authentication.
+ */
+ public void setUserId(String id) {
+ setString(INDEX_USER_ID, MAX_USER_ID_LENGTH, id);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder buf = new StringBuilder(50);
+ buf.append("Version: ");
+ buf.append(Integer.toHexString(getVersionNumber()));
+ buf.append(" Command: ");
+ buf.append(Integer.toHexString(getCommandOrResult()));
+ buf.append(" Port: ");
+ buf.append(getPort());
+ buf.append(" IP: ");
+ buf.append(Integer.toHexString(getIP()));
+ buf.append(" User ID: ");
+ buf.append(getUserId());
+ return buf.toString();
+ }
+
+ /**
+ * Answer the total number of bytes used for the request. This method
+ * searches for the end of the user id, then searches for the end of the
+ * password and returns the final index as the requests length.
+ */
+ public int getLength() {
+ int index = 0;
+
+ // Look for the end of the user id.
+ for (index = INDEX_USER_ID; buffer[index] != 0; index++) {
+ /*
+ * Finds the end of the user id by searching for the null
+ * termination of the user id string.
+ */
+ }
+
+ // Increment the index to include the NULL character in the length;
+ index++;
+ return index;
+ }
+
+ /**
+ * Answer an error string corresponding to the given error value.
+ */
+ public String getErrorString(int error) {
+ switch (error) {
+ case RETURN_FAILURE:
+ return org.apache.harmony.luni.util.Msg.getString("K00cd");
+ case RETURN_CANNOT_CONNECT_TO_IDENTD:
+ return org.apache.harmony.luni.util.Msg.getString("K00ce");
+ case RETURN_DIFFERENT_USER_IDS:
+ return org.apache.harmony.luni.util.Msg.getString("K00cf");
+ default:
+ return org.apache.harmony.luni.util.Msg.getString("K00d0");
+ }
+ }
+
+ /**
+ * Answer the message's byte buffer.
+ */
+ public byte[] getBytes() {
+ return buffer;
+ }
+
+ /**
+ * Get a 16 bit integer from the buffer at the offset given.
+ */
+ private int getInt16(int offset) {
+ return (((buffer[offset] & 0xFF) << 8) + (buffer[offset + 1] & 0xFF));
+ }
+
+ /**
+ * Get a 32 bit integer from the buffer at the offset given.
+ */
+ private int getInt32(int offset) {
+ return ((buffer[offset + 3] & 0xFF) + ((buffer[offset + 2] & 0xFF) << 8)
+ + ((buffer[offset + 1] & 0xFF) << 16) + ((buffer[offset + 0] & 0xFF) << 24));
+ }
+
+ /**
+ * Get a String from the buffer at the offset given. The method reads until
+ * it encounters a null value or reaches the maxLength given.
+ */
+ private String getString(int offset, int maxLength) {
+ int index = offset;
+ int lastIndex = index + maxLength;
+ String result;
+
+ while (index < lastIndex && (buffer[index] != 0)) {
+ index++;
+ }
+ try {
+ result = new String(buffer, offset, index - offset, "ISO8859_1");
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException(e.toString());
+ }
+ return result;
+ }
+
+ /**
+ * Answer the SOCKS version number. Should always be 4.
+ */
+ private int getVersionNumber() {
+ return buffer[INDEX_VERSION];
+ }
+
+ /**
+ * Put a 16 bit integer into the buffer at the offset given.
+ */
+ private void setInt16(int offset, int value) {
+ buffer[offset] = (byte) (value >>> 8 & 0xFF);
+ buffer[offset + 1] = (byte) (value & 0xFF);
+ }
+
+ /**
+ * Put a string into the buffer at the offset given.
+ */
+ private void setString(int offset, int maxLength, String theString) {
+ byte[] stringBytes;
+ try {
+ stringBytes = theString.getBytes("ISO8859_1");
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException(e.toString());
+ }
+ int length = Math.min(stringBytes.length, maxLength);
+ System.arraycopy(stringBytes, 0, buffer, offset, length);
+ buffer[offset + length] = 0;
+ }
+
+ /**
+ * Set the SOCKS version number. This should always be 4.
+ */
+ private void setVersionNumber(int number) {
+ buffer[INDEX_VERSION] = (byte) number;
+ }
}
|