1
0
Fork 0
mirror of https://codeberg.org/Mercury-IM/Smack synced 2025-12-07 13:41:08 +01:00

merged branch improve_bytestreams in trunk

git-svn-id: http://svn.igniterealtime.org/svn/repos/smack/trunk@11821 b35dd754-fafc-0310-a699-88a17e54d16e
This commit is contained in:
Henning Staib 2010-08-15 11:57:11 +00:00 committed by henning
parent ef74695a1b
commit 8b54f34153
74 changed files with 11866 additions and 1902 deletions

View file

@ -0,0 +1,308 @@
/**
* All rights reserved. Licensed 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 org.jivesoftware.smackx.bytestreams.socks5;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.bytestreams.BytestreamRequest;
import org.jivesoftware.smackx.bytestreams.socks5.InitiationListener;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamListener;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamManager;
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.powermock.reflect.Whitebox;
/**
* Test for the InitiationListener class.
*
* @author Henning Staib
*/
public class InitiationListenerTest {
String initiatorJID = "initiator@xmpp-server/Smack";
String targetJID = "target@xmpp-server/Smack";
String xmppServer = "xmpp-server";
String proxyJID = "proxy.xmpp-server";
String proxyAddress = "127.0.0.1";
String sessionID = "session_id";
Connection connection;
Socks5BytestreamManager byteStreamManager;
InitiationListener initiationListener;
Bytestream initBytestream;
/**
* Initialize fields used in the tests.
*/
@Before
public void setup() {
// mock connection
connection = mock(Connection.class);
// create service discovery manager for mocked connection
new ServiceDiscoveryManager(connection);
// initialize Socks5ByteStreamManager to get the InitiationListener
byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
// get the InitiationListener from Socks5ByteStreamManager
initiationListener = Whitebox.getInternalState(byteStreamManager, InitiationListener.class);
// create a SOCKS5 Bytestream initiation packet
initBytestream = Socks5PacketUtils.createBytestreamInitiation(initiatorJID, targetJID,
sessionID);
initBytestream.addStreamHost(proxyJID, proxyAddress, 7777);
}
/**
* If no listeners are registered for incoming SOCKS5 Bytestream requests, all request should be
* rejected with an error.
*
* @throws Exception should not happen
*/
@Test
public void shouldRespondWithError() throws Exception {
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// capture reply to the SOCKS5 Bytestream initiation
ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
verify(connection).sendPacket(argument.capture());
// assert that reply is the correct error packet
assertEquals(initiatorJID, argument.getValue().getTo());
assertEquals(IQ.Type.ERROR, argument.getValue().getType());
assertEquals(XMPPError.Condition.no_acceptable.toString(),
argument.getValue().getError().getCondition());
}
/**
* If a listener for all requests is registered it should be notified on incoming requests.
*
* @throws Exception should not happen
*/
@Test
public void shouldInvokeListenerForAllRequests() throws Exception {
// add listener
Socks5BytestreamListener listener = mock(Socks5BytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(listener);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert listener is called once
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(listener).incomingBytestreamRequest(byteStreamRequest.capture());
// assert that listener is called for the correct request
assertEquals(initiatorJID, byteStreamRequest.getValue().getFrom());
}
/**
* If a listener for a specific user in registered it should be notified on incoming requests
* for that user.
*
* @throws Exception should not happen
*/
@Test
public void shouldInvokeListenerForUser() throws Exception {
// add listener
Socks5BytestreamListener listener = mock(Socks5BytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(listener, initiatorJID);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert listener is called once
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(listener).incomingBytestreamRequest(byteStreamRequest.capture());
// assert that reply is the correct error packet
assertEquals(initiatorJID, byteStreamRequest.getValue().getFrom());
}
/**
* If listener for a specific user is registered it should not be notified on incoming requests
* from other users.
*
* @throws Exception should not happen
*/
@Test
public void shouldNotInvokeListenerForUser() throws Exception {
// add listener for request of user "other_initiator"
Socks5BytestreamListener listener = mock(Socks5BytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(listener, "other_" + initiatorJID);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert listener is not called
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(listener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
// capture reply to the SOCKS5 Bytestream initiation
ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
verify(connection).sendPacket(argument.capture());
// assert that reply is the correct error packet
assertEquals(initiatorJID, argument.getValue().getTo());
assertEquals(IQ.Type.ERROR, argument.getValue().getType());
assertEquals(XMPPError.Condition.no_acceptable.toString(),
argument.getValue().getError().getCondition());
}
/**
* If a user specific listener and an all requests listener is registered only the user specific
* listener should be notified.
*
* @throws Exception should not happen
*/
@Test
public void shouldNotInvokeAllRequestsListenerIfUserListenerExists() throws Exception {
// add listener for all request
Socks5BytestreamListener allRequestsListener = mock(Socks5BytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(allRequestsListener);
// add listener for request of user "initiator"
Socks5BytestreamListener userRequestsListener = mock(Socks5BytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(userRequestsListener, initiatorJID);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert user request listener is called once
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(userRequestsListener).incomingBytestreamRequest(byteStreamRequest.capture());
// assert all requests listener is not called
byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(allRequestsListener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
}
/**
* If a user specific listener and an all requests listener is registered only the all requests
* listener should be notified on an incoming request for another user.
*
* @throws Exception should not happen
*/
@Test
public void shouldInvokeAllRequestsListenerIfUserListenerExists() throws Exception {
// add listener for all request
Socks5BytestreamListener allRequestsListener = mock(Socks5BytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(allRequestsListener);
// add listener for request of user "other_initiator"
Socks5BytestreamListener userRequestsListener = mock(Socks5BytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(userRequestsListener, "other_"
+ initiatorJID);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert user request listener is not called
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(userRequestsListener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
// assert all requests listener is called
byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(allRequestsListener).incomingBytestreamRequest(byteStreamRequest.capture());
}
/**
* If a request with a specific session ID should be ignored no listeners should be notified.
*
* @throws Exception should not happen
*/
@Test
public void shouldIgnoreSocks5BytestreamRequestOnce() throws Exception {
// add listener for all request
Socks5BytestreamListener allRequestsListener = mock(Socks5BytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(allRequestsListener);
// add listener for request of user "initiator"
Socks5BytestreamListener userRequestsListener = mock(Socks5BytestreamListener.class);
byteStreamManager.addIncomingBytestreamListener(userRequestsListener, initiatorJID);
// ignore session ID
byteStreamManager.ignoreBytestreamRequestOnce(sessionID);
// run the listener with the initiation packet
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert user request listener is not called
ArgumentCaptor<BytestreamRequest> byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(userRequestsListener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
// assert all requests listener is not called
byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(allRequestsListener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
// run the listener with the initiation packet again
initiationListener.processPacket(initBytestream);
// wait because packet is processed in an extra thread
Thread.sleep(200);
// assert user request listener is called on the second request with the same session ID
verify(userRequestsListener).incomingBytestreamRequest(byteStreamRequest.capture());
// assert all requests listener is not called
byteStreamRequest = ArgumentCaptor.forClass(BytestreamRequest.class);
verify(allRequestsListener, never()).incomingBytestreamRequest(byteStreamRequest.capture());
}
}

View file

@ -0,0 +1,429 @@
/**
* All rights reserved. Licensed 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 org.jivesoftware.smackx.bytestreams.socks5;
import static org.junit.Assert.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamManager;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamRequest;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5Utils;
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream;
import org.jivesoftware.util.ConnectionUtils;
import org.jivesoftware.util.Protocol;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the Socks5BytestreamRequest class.
*
* @author Henning Staib
*/
public class Socks5ByteStreamRequestTest {
// settings
String initiatorJID = "initiator@xmpp-server/Smack";
String targetJID = "target@xmpp-server/Smack";
String xmppServer = "xmpp-server";
String proxyJID = "proxy.xmpp-server";
String proxyAddress = "127.0.0.1";
String sessionID = "session_id";
Protocol protocol;
Connection connection;
/**
* Initialize fields used in the tests.
*/
@Before
public void setup() {
// build protocol verifier
protocol = new Protocol();
// create mocked XMPP connection
connection = ConnectionUtils.createMockedConnection(protocol, targetJID, xmppServer);
}
/**
* Accepting a SOCKS5 Bytestream request should fail if the request doesn't contain any Socks5
* proxies.
*
* @throws Exception should not happen
*/
@Test
public void shouldFailIfRequestHasNoStreamHosts() throws Exception {
try {
// build SOCKS5 Bytestream initialization request with no SOCKS5 proxies
Bytestream bytestreamInitialization = Socks5PacketUtils.createBytestreamInitiation(
initiatorJID, targetJID, sessionID);
// get SOCKS5 Bytestream manager for connection
Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
// build SOCKS5 Bytestream request with the bytestream initialization
Socks5BytestreamRequest byteStreamRequest = new Socks5BytestreamRequest(
byteStreamManager, bytestreamInitialization);
// accept the stream (this is the call that is tested here)
byteStreamRequest.accept();
fail("exception should be thrown");
}
catch (XMPPException e) {
assertTrue(e.getMessage().contains("Could not establish socket with any provided host"));
}
// verify targets response
assertEquals(1, protocol.getRequests().size());
Packet targetResponse = protocol.getRequests().remove(0);
assertTrue(IQ.class.isInstance(targetResponse));
assertEquals(initiatorJID, targetResponse.getTo());
assertEquals(IQ.Type.ERROR, ((IQ) targetResponse).getType());
assertEquals(XMPPError.Condition.item_not_found.toString(),
((IQ) targetResponse).getError().getCondition());
}
/**
* Accepting a SOCKS5 Bytestream request should fail if target is not able to connect to any of
* the provided SOCKS5 proxies.
*
* @throws Exception
*/
@Test
public void shouldFailIfRequestHasInvalidStreamHosts() throws Exception {
try {
// build SOCKS5 Bytestream initialization request
Bytestream bytestreamInitialization = Socks5PacketUtils.createBytestreamInitiation(
initiatorJID, targetJID, sessionID);
// add proxy that is not running
bytestreamInitialization.addStreamHost(proxyJID, proxyAddress, 7778);
// get SOCKS5 Bytestream manager for connection
Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
// build SOCKS5 Bytestream request with the bytestream initialization
Socks5BytestreamRequest byteStreamRequest = new Socks5BytestreamRequest(
byteStreamManager, bytestreamInitialization);
// accept the stream (this is the call that is tested here)
byteStreamRequest.accept();
fail("exception should be thrown");
}
catch (XMPPException e) {
assertTrue(e.getMessage().contains("Could not establish socket with any provided host"));
}
// verify targets response
assertEquals(1, protocol.getRequests().size());
Packet targetResponse = protocol.getRequests().remove(0);
assertTrue(IQ.class.isInstance(targetResponse));
assertEquals(initiatorJID, targetResponse.getTo());
assertEquals(IQ.Type.ERROR, ((IQ) targetResponse).getType());
assertEquals(XMPPError.Condition.item_not_found.toString(),
((IQ) targetResponse).getError().getCondition());
}
/**
* Target should not try to connect to SOCKS5 proxies that already failed twice.
*
* @throws Exception should not happen
*/
@Test
public void shouldBlacklistInvalidProxyAfter2Failures() throws Exception {
// build SOCKS5 Bytestream initialization request
Bytestream bytestreamInitialization = Socks5PacketUtils.createBytestreamInitiation(
initiatorJID, targetJID, sessionID);
bytestreamInitialization.addStreamHost("invalid." + proxyJID, "127.0.0.2", 7778);
// get SOCKS5 Bytestream manager for connection
Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
// try to connect several times
for (int i = 0; i < 2; i++) {
try {
// build SOCKS5 Bytestream request with the bytestream initialization
Socks5BytestreamRequest byteStreamRequest = new Socks5BytestreamRequest(
byteStreamManager, bytestreamInitialization);
// set timeouts
byteStreamRequest.setTotalConnectTimeout(600);
byteStreamRequest.setMinimumConnectTimeout(300);
// accept the stream (this is the call that is tested here)
byteStreamRequest.accept();
fail("exception should be thrown");
}
catch (XMPPException e) {
assertTrue(e.getMessage().contains(
"Could not establish socket with any provided host"));
}
// verify targets response
assertEquals(1, protocol.getRequests().size());
Packet targetResponse = protocol.getRequests().remove(0);
assertTrue(IQ.class.isInstance(targetResponse));
assertEquals(initiatorJID, targetResponse.getTo());
assertEquals(IQ.Type.ERROR, ((IQ) targetResponse).getType());
assertEquals(XMPPError.Condition.item_not_found.toString(),
((IQ) targetResponse).getError().getCondition());
}
// create test data for stream
byte[] data = new byte[] { 1, 2, 3 };
Socks5TestProxy socks5Proxy = Socks5TestProxy.getProxy(7779);
assertTrue(socks5Proxy.isRunning());
// add a valid SOCKS5 proxy
bytestreamInitialization.addStreamHost(proxyJID, proxyAddress, 7779);
// build SOCKS5 Bytestream request with the bytestream initialization
Socks5BytestreamRequest byteStreamRequest = new Socks5BytestreamRequest(byteStreamManager,
bytestreamInitialization);
// set timeouts
byteStreamRequest.setTotalConnectTimeout(600);
byteStreamRequest.setMinimumConnectTimeout(300);
// accept the stream (this is the call that is tested here)
InputStream inputStream = byteStreamRequest.accept().getInputStream();
// create digest to get the socket opened by target
String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);
// test stream by sending some data
OutputStream outputStream = socks5Proxy.getSocket(digest).getOutputStream();
outputStream.write(data);
// verify that data is transferred correctly
byte[] result = new byte[3];
inputStream.read(result);
assertArrayEquals(data, result);
// verify targets response
assertEquals(1, protocol.getRequests().size());
Packet targetResponse = protocol.getRequests().remove(0);
assertEquals(Bytestream.class, targetResponse.getClass());
assertEquals(initiatorJID, targetResponse.getTo());
assertEquals(IQ.Type.RESULT, ((Bytestream) targetResponse).getType());
assertEquals(proxyJID, ((Bytestream) targetResponse).getUsedHost().getJID());
}
/**
* Target should not not blacklist any SOCKS5 proxies regardless of failing connections.
*
* @throws Exception should not happen
*/
@Test
public void shouldNotBlacklistInvalidProxy() throws Exception {
// disable blacklisting
Socks5BytestreamRequest.setConnectFailureThreshold(0);
// build SOCKS5 Bytestream initialization request
Bytestream bytestreamInitialization = Socks5PacketUtils.createBytestreamInitiation(
initiatorJID, targetJID, sessionID);
bytestreamInitialization.addStreamHost("invalid." + proxyJID, "127.0.0.2", 7778);
// get SOCKS5 Bytestream manager for connection
Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
// try to connect several times
for (int i = 0; i < 10; i++) {
try {
// build SOCKS5 Bytestream request with the bytestream initialization
Socks5BytestreamRequest byteStreamRequest = new Socks5BytestreamRequest(
byteStreamManager, bytestreamInitialization);
// set timeouts
byteStreamRequest.setTotalConnectTimeout(600);
byteStreamRequest.setMinimumConnectTimeout(300);
// accept the stream (this is the call that is tested here)
byteStreamRequest.accept();
fail("exception should be thrown");
}
catch (XMPPException e) {
assertTrue(e.getMessage().contains(
"Could not establish socket with any provided host"));
}
// verify targets response
assertEquals(1, protocol.getRequests().size());
Packet targetResponse = protocol.getRequests().remove(0);
assertTrue(IQ.class.isInstance(targetResponse));
assertEquals(initiatorJID, targetResponse.getTo());
assertEquals(IQ.Type.ERROR, ((IQ) targetResponse).getType());
assertEquals(XMPPError.Condition.item_not_found.toString(),
((IQ) targetResponse).getError().getCondition());
}
// enable blacklisting
Socks5BytestreamRequest.setConnectFailureThreshold(2);
}
/**
* If the SOCKS5 Bytestream request contains multiple SOCKS5 proxies and the first one doesn't
* respond, the connection attempt to this proxy should not consume the whole timeout for
* connecting to the proxies.
*
* @throws Exception should not happen
*/
@Test
public void shouldNotTimeoutIfFirstSocks5ProxyDoesNotRespond() throws Exception {
// start a local SOCKS5 proxy
Socks5TestProxy socks5Proxy = Socks5TestProxy.getProxy(7778);
// create a fake SOCKS5 proxy that doesn't respond to a request
ServerSocket serverSocket = new ServerSocket(7779);
// build SOCKS5 Bytestream initialization request
Bytestream bytestreamInitialization = Socks5PacketUtils.createBytestreamInitiation(
initiatorJID, targetJID, sessionID);
bytestreamInitialization.addStreamHost(proxyJID, proxyAddress, 7779);
bytestreamInitialization.addStreamHost(proxyJID, proxyAddress, 7778);
// create test data for stream
byte[] data = new byte[] { 1, 2, 3 };
// get SOCKS5 Bytestream manager for connection
Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
// build SOCKS5 Bytestream request with the bytestream initialization
Socks5BytestreamRequest byteStreamRequest = new Socks5BytestreamRequest(byteStreamManager,
bytestreamInitialization);
// set timeouts
byteStreamRequest.setTotalConnectTimeout(2000);
byteStreamRequest.setMinimumConnectTimeout(1000);
// accept the stream (this is the call that is tested here)
InputStream inputStream = byteStreamRequest.accept().getInputStream();
// assert that client tries to connect to dumb SOCKS5 proxy
Socket socket = serverSocket.accept();
assertNotNull(socket);
// create digest to get the socket opened by target
String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);
// test stream by sending some data
OutputStream outputStream = socks5Proxy.getSocket(digest).getOutputStream();
outputStream.write(data);
// verify that data is transferred correctly
byte[] result = new byte[3];
inputStream.read(result);
assertArrayEquals(data, result);
// verify targets response
assertEquals(1, protocol.getRequests().size());
Packet targetResponse = protocol.getRequests().remove(0);
assertEquals(Bytestream.class, targetResponse.getClass());
assertEquals(initiatorJID, targetResponse.getTo());
assertEquals(IQ.Type.RESULT, ((Bytestream) targetResponse).getType());
assertEquals(proxyJID, ((Bytestream) targetResponse).getUsedHost().getJID());
serverSocket.close();
}
/**
* Accepting the SOCKS5 Bytestream request should be successfully.
*
* @throws Exception should not happen
*/
@Test
public void shouldAcceptSocks5BytestreamRequestAndReceiveData() throws Exception {
// start a local SOCKS5 proxy
Socks5TestProxy socks5Proxy = Socks5TestProxy.getProxy(7778);
// build SOCKS5 Bytestream initialization request
Bytestream bytestreamInitialization = Socks5PacketUtils.createBytestreamInitiation(
initiatorJID, targetJID, sessionID);
bytestreamInitialization.addStreamHost(proxyJID, proxyAddress, 7778);
// create test data for stream
byte[] data = new byte[] { 1, 2, 3 };
// get SOCKS5 Bytestream manager for connection
Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
// build SOCKS5 Bytestream request with the bytestream initialization
Socks5BytestreamRequest byteStreamRequest = new Socks5BytestreamRequest(byteStreamManager,
bytestreamInitialization);
// accept the stream (this is the call that is tested here)
InputStream inputStream = byteStreamRequest.accept().getInputStream();
// create digest to get the socket opened by target
String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);
// test stream by sending some data
OutputStream outputStream = socks5Proxy.getSocket(digest).getOutputStream();
outputStream.write(data);
// verify that data is transferred correctly
byte[] result = new byte[3];
inputStream.read(result);
assertArrayEquals(data, result);
// verify targets response
assertEquals(1, protocol.getRequests().size());
Packet targetResponse = protocol.getRequests().remove(0);
assertEquals(Bytestream.class, targetResponse.getClass());
assertEquals(initiatorJID, targetResponse.getTo());
assertEquals(IQ.Type.RESULT, ((Bytestream) targetResponse).getType());
assertEquals(proxyJID, ((Bytestream) targetResponse).getUsedHost().getJID());
}
/**
* Stop eventually started local SOCKS5 test proxy.
*/
@After
public void cleanUp() {
Socks5TestProxy.stopProxy();
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
}
}

View file

@ -0,0 +1,310 @@
/**
* All rights reserved. Licensed 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 org.jivesoftware.smackx.bytestreams.socks5;
import static org.junit.Assert.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5Client;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5ClientForInitiator;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5Proxy;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5Utils;
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream;
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream.StreamHost;
import org.jivesoftware.util.ConnectionUtils;
import org.jivesoftware.util.Protocol;
import org.jivesoftware.util.Verification;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Test for Socks5ClientForInitiator class.
*
* @author Henning Staib
*/
public class Socks5ClientForInitiatorTest {
// settings
String initiatorJID = "initiator@xmpp-server/Smack";
String targetJID = "target@xmpp-server/Smack";
String xmppServer = "xmpp-server";
String proxyJID = "proxy.xmpp-server";
String proxyAddress = "127.0.0.1";
int proxyPort = 7890;
String sessionID = "session_id";
// protocol verifier
Protocol protocol;
// mocked XMPP connection
Connection connection;
/**
* Initialize fields used in the tests.
*/
@Before
public void setup() {
// build protocol verifier
protocol = new Protocol();
// create mocked XMPP connection
connection = ConnectionUtils.createMockedConnection(protocol, initiatorJID, xmppServer);
}
/**
* If the target is not connected to the local SOCKS5 proxy an exception should be thrown.
*
* @throws Exception should not happen
*/
@Test
public void shouldFailIfTargetIsNotConnectedToLocalSocks5Proxy() throws Exception {
// start a local SOCKS5 proxy
SmackConfiguration.setLocalSocks5ProxyPort(proxyPort);
Socks5Proxy socks5Proxy = Socks5Proxy.getSocks5Proxy();
socks5Proxy.start();
// build stream host information for local SOCKS5 proxy
StreamHost streamHost = new StreamHost(connection.getUser(),
socks5Proxy.getLocalAddresses().get(0));
streamHost.setPort(socks5Proxy.getPort());
// create digest to get the socket opened by target
String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);
Socks5ClientForInitiator socks5Client = new Socks5ClientForInitiator(streamHost, digest,
connection, sessionID, targetJID);
try {
socks5Client.getSocket(10000);
fail("exception should be thrown");
}
catch (XMPPException e) {
assertTrue(e.getMessage().contains("target is not connected to SOCKS5 proxy"));
protocol.verifyAll(); // assert no XMPP messages were sent
}
socks5Proxy.stop();
}
/**
* Initiator and target should successfully connect to the local SOCKS5 proxy.
*
* @throws Exception should not happen
*/
@Test
public void shouldSuccessfullyConnectThroughLocalSocks5Proxy() throws Exception {
// start a local SOCKS5 proxy
SmackConfiguration.setLocalSocks5ProxyPort(proxyPort);
Socks5Proxy socks5Proxy = Socks5Proxy.getSocks5Proxy();
socks5Proxy.start();
// test data
final byte[] data = new byte[] { 1, 2, 3 };
// create digest
final String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);
// allow connection of target with this digest
socks5Proxy.addTransfer(digest);
// build stream host information
final StreamHost streamHost = new StreamHost(connection.getUser(),
socks5Proxy.getLocalAddresses().get(0));
streamHost.setPort(socks5Proxy.getPort());
// target connects to local SOCKS5 proxy
Thread targetThread = new Thread() {
@Override
public void run() {
try {
Socks5Client targetClient = new Socks5Client(streamHost, digest);
Socket socket = targetClient.getSocket(10000);
socket.getOutputStream().write(data);
}
catch (Exception e) {
fail(e.getMessage());
}
}
};
targetThread.start();
Thread.sleep(200);
// initiator connects
Socks5ClientForInitiator socks5Client = new Socks5ClientForInitiator(streamHost, digest,
connection, sessionID, targetJID);
Socket socket = socks5Client.getSocket(10000);
// verify test data
InputStream in = socket.getInputStream();
for (int i = 0; i < data.length; i++) {
assertEquals(data[i], in.read());
}
targetThread.join();
protocol.verifyAll(); // assert no XMPP messages were sent
socks5Proxy.removeTransfer(digest);
socks5Proxy.stop();
}
/**
* If the initiator can connect to a SOCKS5 proxy but activating the stream fails an exception
* should be thrown.
*
* @throws Exception should not happen
*/
@Test
public void shouldFailIfActivateSocks5ProxyFails() throws Exception {
// build error response as reply to the stream activation
XMPPError xmppError = new XMPPError(XMPPError.Condition.interna_server_error);
IQ error = new IQ() {
public String getChildElementXML() {
return null;
}
};
error.setType(Type.ERROR);
error.setFrom(proxyJID);
error.setTo(initiatorJID);
error.setError(xmppError);
protocol.addResponse(error, Verification.correspondingSenderReceiver,
Verification.requestTypeSET);
// start a local SOCKS5 proxy
Socks5TestProxy socks5Proxy = Socks5TestProxy.getProxy(proxyPort);
socks5Proxy.start();
StreamHost streamHost = new StreamHost(proxyJID, socks5Proxy.getAddress());
streamHost.setPort(socks5Proxy.getPort());
// create digest to get the socket opened by target
String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);
Socks5ClientForInitiator socks5Client = new Socks5ClientForInitiator(streamHost, digest,
connection, sessionID, targetJID);
try {
socks5Client.getSocket(10000);
fail("exception should be thrown");
}
catch (XMPPException e) {
assertTrue(e.getMessage().contains("activating SOCKS5 Bytestream failed"));
protocol.verifyAll();
}
socks5Proxy.stop();
}
/**
* Target and initiator should successfully connect to a "remote" SOCKS5 proxy and the initiator
* activates the bytestream.
*
* @throws Exception should not happen
*/
@Test
public void shouldSuccessfullyEstablishConnectionAndActivateSocks5Proxy() throws Exception {
// build activation confirmation response
IQ activationResponse = new IQ() {
@Override
public String getChildElementXML() {
return null;
}
};
activationResponse.setFrom(proxyJID);
activationResponse.setTo(initiatorJID);
activationResponse.setType(IQ.Type.RESULT);
protocol.addResponse(activationResponse, Verification.correspondingSenderReceiver,
Verification.requestTypeSET, new Verification<Bytestream, IQ>() {
public void verify(Bytestream request, IQ response) {
// verify that the correct stream should be activated
assertNotNull(request.getToActivate());
assertEquals(targetJID, request.getToActivate().getTarget());
}
});
// start a local SOCKS5 proxy
Socks5TestProxy socks5Proxy = Socks5TestProxy.getProxy(proxyPort);
socks5Proxy.start();
StreamHost streamHost = new StreamHost(proxyJID, socks5Proxy.getAddress());
streamHost.setPort(socks5Proxy.getPort());
// create digest to get the socket opened by target
String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);
Socks5ClientForInitiator socks5Client = new Socks5ClientForInitiator(streamHost, digest,
connection, sessionID, targetJID);
Socket initiatorSocket = socks5Client.getSocket(10000);
InputStream in = initiatorSocket.getInputStream();
Socket targetSocket = socks5Proxy.getSocket(digest);
OutputStream out = targetSocket.getOutputStream();
// verify test data
for (int i = 0; i < 10; i++) {
out.write(i);
assertEquals(i, in.read());
}
protocol.verifyAll();
initiatorSocket.close();
targetSocket.close();
socks5Proxy.stop();
}
/**
* Reset default port for local SOCKS5 proxy.
*/
@After
public void cleanup() {
SmackConfiguration.setLocalSocks5ProxyPort(7777);
}
}

View file

@ -0,0 +1,332 @@
/**
* All rights reserved. Licensed 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 org.jivesoftware.smackx.bytestreams.socks5;
import static org.junit.Assert.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5Client;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5Utils;
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream.StreamHost;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Test for Socks5Client class.
*
* @author Henning Staib
*/
public class Socks5ClientTest {
// settings
private String serverAddress = "127.0.0.1";
private int serverPort = 7890;
private String proxyJID = "proxy.xmpp-server";
private String digest = "digest";
private ServerSocket serverSocket;
/**
* Initialize fields used in the tests.
*
* @throws Exception should not happen
*/
@Before
public void setup() throws Exception {
// create SOCKS5 proxy server socket
serverSocket = new ServerSocket(serverPort);
}
/**
* A SOCKS5 client MUST close connection if server doesn't accept any of the given
* authentication methods. (See RFC1928 Section 3)
*
* @throws Exception should not happen
*/
@Test
public void shouldCloseSocketIfServerDoesNotAcceptAuthenticationMethod() throws Exception {
// start thread to connect to SOCKS5 proxy
Thread serverThread = new Thread() {
@Override
public void run() {
StreamHost streamHost = new StreamHost(proxyJID, serverAddress);
streamHost.setPort(serverPort);
Socks5Client socks5Client = new Socks5Client(streamHost, digest);
try {
socks5Client.getSocket(10000);
fail("exception should be thrown");
}
catch (XMPPException e) {
assertTrue(e.getMessage().contains(
"establishing connection to SOCKS5 proxy failed"));
}
catch (Exception e) {
fail(e.getMessage());
}
}
};
serverThread.start();
// accept connection form client
Socket socket = serverSocket.accept();
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// validate authentication request
assertEquals((byte) 0x05, (byte) in.read()); // version
assertEquals((byte) 0x01, (byte) in.read()); // number of supported auth methods
assertEquals((byte) 0x00, (byte) in.read()); // no-authentication method
// respond that no authentication method is accepted
out.write(new byte[] { (byte) 0x05, (byte) 0xFF });
out.flush();
// wait for client to shutdown
serverThread.join();
// assert socket is closed
assertEquals(-1, in.read());
}
/**
* The SOCKS5 client should close connection if server replies in an unsupported way.
*
* @throws Exception should not happen
*/
@Test
public void shouldCloseSocketIfServerRepliesInUnsupportedWay() throws Exception {
// start thread to connect to SOCKS5 proxy
Thread serverThread = new Thread() {
@Override
public void run() {
StreamHost streamHost = new StreamHost(proxyJID, serverAddress);
streamHost.setPort(serverPort);
Socks5Client socks5Client = new Socks5Client(streamHost, digest);
try {
socks5Client.getSocket(10000);
fail("exception should be thrown");
}
catch (XMPPException e) {
assertTrue(e.getMessage().contains(
"establishing connection to SOCKS5 proxy failed"));
}
catch (Exception e) {
fail(e.getMessage());
}
}
};
serverThread.start();
// accept connection from client
Socket socket = serverSocket.accept();
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// validate authentication request
assertEquals((byte) 0x05, (byte) in.read()); // version
assertEquals((byte) 0x01, (byte) in.read()); // number of supported auth methods
assertEquals((byte) 0x00, (byte) in.read()); // no-authentication method
// respond that no no-authentication method is used
out.write(new byte[] { (byte) 0x05, (byte) 0x00 });
out.flush();
Socks5Utils.receiveSocks5Message(in);
// reply with unsupported address type
out.write(new byte[] { (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00 });
out.flush();
// wait for client to shutdown
serverThread.join();
// assert socket is closed
assertEquals(-1, in.read());
}
/**
* The SOCKS5 client should close connection if server replies with an error.
*
* @throws Exception should not happen
*/
@Test
public void shouldCloseSocketIfServerRepliesWithError() throws Exception {
// start thread to connect to SOCKS5 proxy
Thread serverThread = new Thread() {
@Override
public void run() {
StreamHost streamHost = new StreamHost(proxyJID, serverAddress);
streamHost.setPort(serverPort);
Socks5Client socks5Client = new Socks5Client(streamHost, digest);
try {
socks5Client.getSocket(10000);
fail("exception should be thrown");
}
catch (XMPPException e) {
assertTrue(e.getMessage().contains(
"establishing connection to SOCKS5 proxy failed"));
}
catch (Exception e) {
fail(e.getMessage());
}
}
};
serverThread.start();
Socket socket = serverSocket.accept();
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// validate authentication request
assertEquals((byte) 0x05, (byte) in.read()); // version
assertEquals((byte) 0x01, (byte) in.read()); // number of supported auth methods
assertEquals((byte) 0x00, (byte) in.read()); // no-authentication method
// respond that no no-authentication method is used
out.write(new byte[] { (byte) 0x05, (byte) 0x00 });
out.flush();
Socks5Utils.receiveSocks5Message(in);
// reply with full SOCKS5 message with an error code (01 = general SOCKS server
// failure)
out.write(new byte[] { (byte) 0x05, (byte) 0x01, (byte) 0x00, (byte) 0x03 });
byte[] address = digest.getBytes();
out.write(address.length);
out.write(address);
out.write(new byte[] { (byte) 0x00, (byte) 0x00 });
out.flush();
// wait for client to shutdown
serverThread.join();
// assert socket is closed
assertEquals(-1, in.read());
}
/**
* The SOCKS5 client should successfully connect to the SOCKS5 server
*
* @throws Exception should not happen
*/
@Test
public void shouldSuccessfullyConnectToSocks5Server() throws Exception {
// start thread to connect to SOCKS5 proxy
Thread serverThread = new Thread() {
@Override
public void run() {
StreamHost streamHost = new StreamHost(proxyJID, serverAddress);
streamHost.setPort(serverPort);
Socks5Client socks5Client = new Socks5Client(streamHost, digest);
try {
Socket socket = socks5Client.getSocket(10000);
assertNotNull(socket);
socket.getOutputStream().write(123);
socket.close();
}
catch (Exception e) {
fail(e.getMessage());
}
}
};
serverThread.start();
Socket socket = serverSocket.accept();
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// validate authentication request
assertEquals((byte) 0x05, (byte) in.read()); // version
assertEquals((byte) 0x01, (byte) in.read()); // number of supported auth methods
assertEquals((byte) 0x00, (byte) in.read()); // no-authentication method
// respond that no no-authentication method is used
out.write(new byte[] { (byte) 0x05, (byte) 0x00 });
out.flush();
byte[] address = digest.getBytes();
assertEquals((byte) 0x05, (byte) in.read()); // version
assertEquals((byte) 0x01, (byte) in.read()); // connect request
assertEquals((byte) 0x00, (byte) in.read()); // reserved byte (always 0)
assertEquals((byte) 0x03, (byte) in.read()); // address type (domain)
assertEquals(address.length, (byte) in.read()); // address length
for (int i = 0; i < address.length; i++) {
assertEquals(address[i], (byte) in.read()); // address
}
assertEquals((byte) 0x00, (byte) in.read()); // port
assertEquals((byte) 0x00, (byte) in.read());
// reply with success SOCKS5 message
out.write(new byte[] { (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x03 });
out.write(address.length);
out.write(address);
out.write(new byte[] { (byte) 0x00, (byte) 0x00 });
out.flush();
// wait for client to shutdown
serverThread.join();
// verify data sent from client
assertEquals(123, in.read());
// assert socket is closed
assertEquals(-1, in.read());
}
/**
* Close fake SOCKS5 proxy.
*
* @throws Exception should not happen
*/
@After
public void cleanup() throws Exception {
serverSocket.close();
}
}

View file

@ -0,0 +1,119 @@
/**
* All rights reserved. Licensed 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 org.jivesoftware.smackx.bytestreams.socks5;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.smackx.packet.DiscoverItems;
/**
* A collection of utility methods to create XMPP packets.
*
* @author Henning Staib
*/
public class Socks5PacketUtils {
/**
* Returns a SOCKS5 Bytestream initialization request packet. The Request doesn't contain any
* SOCKS5 proxies.
*
* @param from the initiator
* @param to the target
* @param sessionID the session ID
* @return SOCKS5 Bytestream initialization request packet
*/
public static Bytestream createBytestreamInitiation(String from, String to, String sessionID) {
Bytestream bytestream = new Bytestream();
bytestream.getPacketID();
bytestream.setFrom(from);
bytestream.setTo(to);
bytestream.setSessionID(sessionID);
bytestream.setType(IQ.Type.SET);
return bytestream;
}
/**
* Returns a response to a SOCKS5 Bytestream initialization request. The packet doesn't contain
* the uses-host information.
*
* @param from the target
* @param to the initiator
* @return response to a SOCKS5 Bytestream initialization request
*/
public static Bytestream createBytestreamResponse(String from, String to) {
Bytestream streamHostInfo = new Bytestream();
streamHostInfo.getPacketID();
streamHostInfo.setFrom(from);
streamHostInfo.setTo(to);
streamHostInfo.setType(IQ.Type.RESULT);
return streamHostInfo;
}
/**
* Returns a response to an item discovery request. The packet doesn't contain any items.
*
* @param from the XMPP server
* @param to the XMPP client
* @return response to an item discovery request
*/
public static DiscoverItems createDiscoverItems(String from, String to) {
DiscoverItems discoverItems = new DiscoverItems();
discoverItems.getPacketID();
discoverItems.setFrom(from);
discoverItems.setTo(to);
discoverItems.setType(IQ.Type.RESULT);
return discoverItems;
}
/**
* Returns a response to an info discovery request. The packet doesn't contain any infos.
*
* @param from the target
* @param to the initiator
* @return response to an info discovery request
*/
public static DiscoverInfo createDiscoverInfo(String from, String to) {
DiscoverInfo discoverInfo = new DiscoverInfo();
discoverInfo.getPacketID();
discoverInfo.setFrom(from);
discoverInfo.setTo(to);
discoverInfo.setType(IQ.Type.RESULT);
return discoverInfo;
}
/**
* Returns a response IQ for a activation request to the proxy.
*
* @param from JID of the proxy
* @param to JID of the client who wants to activate the SOCKS5 Bytestream
* @return response IQ for a activation request to the proxy
*/
public static IQ createActivationConfirmation(String from, String to) {
IQ response = new IQ() {
@Override
public String getChildElementXML() {
return null;
}
};
response.getPacketID();
response.setFrom(from);
response.setTo(to);
response.setType(IQ.Type.RESULT);
return response;
}
}

View file

@ -0,0 +1,360 @@
/**
* All rights reserved. Licensed 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 org.jivesoftware.smackx.bytestreams.socks5;
import static org.junit.Assert.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5Proxy;
import org.junit.After;
import org.junit.Test;
/**
* Test for Socks5Proxy class.
*
* @author Henning Staib
*/
public class Socks5ProxyTest {
/**
* The SOCKS5 proxy should be a singleton used by all XMPP connections
*/
@Test
public void shouldBeASingleton() {
SmackConfiguration.setLocalSocks5ProxyEnabled(false);
Socks5Proxy proxy1 = Socks5Proxy.getSocks5Proxy();
Socks5Proxy proxy2 = Socks5Proxy.getSocks5Proxy();
assertNotNull(proxy1);
assertNotNull(proxy2);
assertSame(proxy1, proxy2);
}
/**
* The SOCKS5 proxy should not be started if disabled by configuration.
*/
@Test
public void shouldNotBeRunningIfDisabled() {
SmackConfiguration.setLocalSocks5ProxyEnabled(false);
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
assertFalse(proxy.isRunning());
}
/**
* The SOCKS5 proxy should use a free port above the one configured.
*
* @throws Exception should not happen
*/
@Test
public void shouldUseFreePortOnNegativeValues() throws Exception {
SmackConfiguration.setLocalSocks5ProxyEnabled(false);
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
assertFalse(proxy.isRunning());
ServerSocket serverSocket = new ServerSocket(0);
SmackConfiguration.setLocalSocks5ProxyPort(-serverSocket.getLocalPort());
proxy.start();
assertTrue(proxy.isRunning());
serverSocket.close();
assertTrue(proxy.getPort() > serverSocket.getLocalPort());
}
/**
* When inserting new network addresses to the proxy the order should remain in the order they
* were inserted.
*/
@Test
public void shouldPreserveAddressOrderOnInsertions() {
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
List<String> addresses = new ArrayList<String>(proxy.getLocalAddresses());
addresses.add("1");
addresses.add("2");
addresses.add("3");
for (String address : addresses) {
proxy.addLocalAddress(address);
}
List<String> localAddresses = proxy.getLocalAddresses();
for (int i = 0; i < addresses.size(); i++) {
assertEquals(addresses.get(i), localAddresses.get(i));
}
}
/**
* When replacing network addresses of the proxy the order should remain in the order if the
* given list.
*/
@Test
public void shouldPreserveAddressOrderOnReplace() {
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
List<String> addresses = new ArrayList<String>(proxy.getLocalAddresses());
addresses.add("1");
addresses.add("2");
addresses.add("3");
proxy.replaceLocalAddresses(addresses);
List<String> localAddresses = proxy.getLocalAddresses();
for (int i = 0; i < addresses.size(); i++) {
assertEquals(addresses.get(i), localAddresses.get(i));
}
}
/**
* Inserting the same address multiple times should not cause the proxy to return this address
* multiple times.
*/
@Test
public void shouldNotReturnMultipleSameAddress() {
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
proxy.addLocalAddress("same");
proxy.addLocalAddress("same");
proxy.addLocalAddress("same");
assertEquals(2, proxy.getLocalAddresses().size());
}
/**
* There should be only one thread executing the SOCKS5 proxy process.
*/
@Test
public void shouldOnlyStartOneServerThread() {
int threadCount = Thread.activeCount();
SmackConfiguration.setLocalSocks5ProxyPort(7890);
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
proxy.start();
assertTrue(proxy.isRunning());
assertEquals(threadCount + 1, Thread.activeCount());
proxy.start();
assertTrue(proxy.isRunning());
assertEquals(threadCount + 1, Thread.activeCount());
proxy.stop();
assertFalse(proxy.isRunning());
assertEquals(threadCount, Thread.activeCount());
proxy.start();
assertTrue(proxy.isRunning());
assertEquals(threadCount + 1, Thread.activeCount());
proxy.stop();
}
/**
* If the SOCKS5 proxy accepts a connection that is not a SOCKS5 connection it should close the
* corresponding socket.
*
* @throws Exception should not happen
*/
@Test
public void shouldCloseSocketIfNoSocks5Request() throws Exception {
SmackConfiguration.setLocalSocks5ProxyPort(7890);
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
proxy.start();
Socket socket = new Socket(proxy.getLocalAddresses().get(0), proxy.getPort());
OutputStream out = socket.getOutputStream();
out.write(new byte[] { 1, 2, 3 });
assertEquals(-1, socket.getInputStream().read());
proxy.stop();
}
/**
* The SOCKS5 proxy should reply with an error message if no supported authentication methods
* are given in the SOCKS5 request.
*
* @throws Exception should not happen
*/
@Test
public void shouldRespondWithErrorIfNoSupportedAuthenticationMethod() throws Exception {
SmackConfiguration.setLocalSocks5ProxyPort(7890);
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
proxy.start();
Socket socket = new Socket(proxy.getLocalAddresses().get(0), proxy.getPort());
OutputStream out = socket.getOutputStream();
// request username/password-authentication
out.write(new byte[] { (byte) 0x05, (byte) 0x01, (byte) 0x02 });
InputStream in = socket.getInputStream();
assertEquals((byte) 0x05, (byte) in.read());
assertEquals((byte) 0xFF, (byte) in.read());
assertEquals(-1, in.read());
proxy.stop();
}
/**
* The SOCKS5 proxy should respond with an error message if the client is not allowed to connect
* with the proxy.
*
* @throws Exception should not happen
*/
@Test
public void shouldRespondWithErrorIfConnectionIsNotAllowed() throws Exception {
SmackConfiguration.setLocalSocks5ProxyPort(7890);
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
proxy.start();
Socket socket = new Socket(proxy.getLocalAddresses().get(0), proxy.getPort());
OutputStream out = socket.getOutputStream();
out.write(new byte[] { (byte) 0x05, (byte) 0x01, (byte) 0x00 });
InputStream in = socket.getInputStream();
assertEquals((byte) 0x05, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
// send valid SOCKS5 message
out.write(new byte[] { (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x01,
(byte) 0xAA, (byte) 0x00, (byte) 0x00 });
// verify error message
assertEquals((byte) 0x05, (byte) in.read());
assertFalse((byte) 0x00 == (byte) in.read()); // something other than 0 == success
assertEquals((byte) 0x00, (byte) in.read());
assertEquals((byte) 0x03, (byte) in.read());
assertEquals((byte) 0x01, (byte) in.read());
assertEquals((byte) 0xAA, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
assertEquals(-1, in.read());
proxy.stop();
}
/**
* A Client should successfully establish a connection to the SOCKS5 proxy.
*
* @throws Exception should not happen
*/
@Test
public void shouldSuccessfullyEstablishConnection() throws Exception {
SmackConfiguration.setLocalSocks5ProxyPort(7890);
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
proxy.start();
assertTrue(proxy.isRunning());
String digest = new String(new byte[] { (byte) 0xAA });
// add digest to allow connection
proxy.addTransfer(digest);
Socket socket = new Socket(proxy.getLocalAddresses().get(0), proxy.getPort());
OutputStream out = socket.getOutputStream();
out.write(new byte[] { (byte) 0x05, (byte) 0x01, (byte) 0x00 });
InputStream in = socket.getInputStream();
assertEquals((byte) 0x05, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
// send valid SOCKS5 message
out.write(new byte[] { (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x01,
(byte) 0xAA, (byte) 0x00, (byte) 0x00 });
// verify response
assertEquals((byte) 0x05, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read()); // success
assertEquals((byte) 0x00, (byte) in.read());
assertEquals((byte) 0x03, (byte) in.read());
assertEquals((byte) 0x01, (byte) in.read());
assertEquals((byte) 0xAA, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
Thread.sleep(200);
Socket remoteSocket = proxy.getSocket(digest);
// remove digest
proxy.removeTransfer(digest);
// test stream
OutputStream remoteOut = remoteSocket.getOutputStream();
byte[] data = new byte[] { 1, 2, 3, 4, 5 };
remoteOut.write(data);
remoteOut.flush();
for (int i = 0; i < data.length; i++) {
assertEquals(data[i], in.read());
}
remoteSocket.close();
assertEquals(-1, in.read());
proxy.stop();
}
/**
* Reset SOCKS5 proxy settings.
*/
@After
public void cleanup() {
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
SmackConfiguration.setLocalSocks5ProxyPort(7777);
Socks5Proxy socks5Proxy = Socks5Proxy.getSocks5Proxy();
try {
String address = InetAddress.getLocalHost().getHostAddress();
List<String> addresses = new ArrayList<String>();
addresses.add(address);
socks5Proxy.replaceLocalAddresses(addresses);
}
catch (UnknownHostException e) {
// ignore
}
socks5Proxy.stop();
}
}

View file

@ -0,0 +1,286 @@
/**
* All rights reserved. Licensed 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 org.jivesoftware.smackx.bytestreams.socks5;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5Utils;
/**
* Simple SOCKS5 proxy for testing purposes. It is almost the same as the Socks5Proxy class but the
* port can be configured more easy and it all connections are allowed.
*
* @author Henning Staib
*/
public class Socks5TestProxy {
/* SOCKS5 proxy singleton */
private static Socks5TestProxy socks5Server;
/* reusable implementation of a SOCKS5 proxy server process */
private Socks5ServerProcess serverProcess;
/* thread running the SOCKS5 server process */
private Thread serverThread;
/* server socket to accept SOCKS5 connections */
private ServerSocket serverSocket;
/* assigns a connection to a digest */
private final Map<String, Socket> connectionMap = new ConcurrentHashMap<String, Socket>();
/* port of the test proxy */
private int port = 7777;
/**
* Private constructor.
*/
private Socks5TestProxy(int port) {
this.serverProcess = new Socks5ServerProcess();
this.port = port;
}
/**
* Returns the local SOCKS5 proxy server
*
* @param port of the test proxy
* @return the local SOCKS5 proxy server
*/
public static synchronized Socks5TestProxy getProxy(int port) {
if (socks5Server == null) {
socks5Server = new Socks5TestProxy(port);
socks5Server.start();
}
return socks5Server;
}
/**
* Stops the test proxy
*/
public static synchronized void stopProxy() {
if (socks5Server != null) {
socks5Server.stop();
socks5Server = null;
}
}
/**
* Starts the local SOCKS5 proxy server. If it is already running, this method does nothing.
*/
public synchronized void start() {
if (isRunning()) {
return;
}
try {
this.serverSocket = new ServerSocket(this.port);
this.serverThread = new Thread(this.serverProcess);
this.serverThread.start();
}
catch (IOException e) {
e.printStackTrace();
// do nothing
}
}
/**
* Stops the local SOCKS5 proxy server. If it is not running this method does nothing.
*/
public synchronized void stop() {
if (!isRunning()) {
return;
}
try {
this.serverSocket.close();
}
catch (IOException e) {
// do nothing
e.printStackTrace();
}
if (this.serverThread != null && this.serverThread.isAlive()) {
try {
this.serverThread.interrupt();
this.serverThread.join();
}
catch (InterruptedException e) {
// do nothing
e.printStackTrace();
}
}
this.serverThread = null;
this.serverSocket = null;
}
/**
* Returns the host address of the local SOCKS5 proxy server.
*
* @return the host address of the local SOCKS5 proxy server
*/
public String getAddress() {
try {
return InetAddress.getLocalHost().getHostAddress();
}
catch (UnknownHostException e) {
return null;
}
}
/**
* Returns the port of the local SOCKS5 proxy server. If it is not running -1 will be returned.
*
* @return the port of the local SOCKS5 proxy server or -1 if proxy is not running
*/
public int getPort() {
if (!isRunning()) {
return -1;
}
return this.serverSocket.getLocalPort();
}
/**
* Returns the socket for the given digest.
*
* @param digest identifying the connection
* @return socket or null if there is no socket for the given digest
*/
public Socket getSocket(String digest) {
return this.connectionMap.get(digest);
}
/**
* Returns true if the local SOCKS5 proxy server is running, otherwise false.
*
* @return true if the local SOCKS5 proxy server is running, otherwise false
*/
public boolean isRunning() {
return this.serverSocket != null;
}
/**
* Implementation of a simplified SOCKS5 proxy server.
*
* @author Henning Staib
*/
class Socks5ServerProcess implements Runnable {
public void run() {
while (true) {
Socket socket = null;
try {
if (Socks5TestProxy.this.serverSocket.isClosed()
|| Thread.currentThread().isInterrupted()) {
return;
}
// accept connection
socket = Socks5TestProxy.this.serverSocket.accept();
// initialize connection
establishConnection(socket);
}
catch (SocketException e) {
/* do nothing */
}
catch (Exception e) {
try {
e.printStackTrace();
socket.close();
}
catch (IOException e1) {
/* Do Nothing */
}
}
}
}
/**
* Negotiates a SOCKS5 connection and stores it on success.
*
* @param socket connection to the client
* @throws XMPPException if client requests a connection in an unsupported way
* @throws IOException if a network error occurred
*/
private void establishConnection(Socket socket) throws XMPPException, IOException {
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
DataInputStream in = new DataInputStream(socket.getInputStream());
// first byte is version should be 5
int b = in.read();
if (b != 5) {
throw new XMPPException("Only SOCKS5 supported");
}
// second byte number of authentication methods supported
b = in.read();
// read list of supported authentication methods
byte[] auth = new byte[b];
in.readFully(auth);
byte[] authMethodSelectionResponse = new byte[2];
authMethodSelectionResponse[0] = (byte) 0x05; // protocol version
// only authentication method 0, no authentication, supported
boolean noAuthMethodFound = false;
for (int i = 0; i < auth.length; i++) {
if (auth[i] == (byte) 0x00) {
noAuthMethodFound = true;
break;
}
}
if (!noAuthMethodFound) {
authMethodSelectionResponse[1] = (byte) 0xFF; // no acceptable methods
out.write(authMethodSelectionResponse);
out.flush();
throw new XMPPException("Authentication method not supported");
}
authMethodSelectionResponse[1] = (byte) 0x00; // no-authentication method
out.write(authMethodSelectionResponse);
out.flush();
// receive connection request
byte[] connectionRequest = Socks5Utils.receiveSocks5Message(in);
// extract digest
String responseDigest = new String(connectionRequest, 5, connectionRequest[4]);
connectionRequest[1] = (byte) 0x00; // set return status to 0 (success)
out.write(connectionRequest);
out.flush();
// store connection
Socks5TestProxy.this.connectionMap.put(responseDigest, socket);
}
}
}