beginning of format, updated imports. (shendaras)
This commit is contained in:
@ -44,6 +44,7 @@ class ClientEngine {
|
|||||||
if (_log.shouldLog(Log.INFO))
|
if (_log.shouldLog(Log.INFO))
|
||||||
_log.info("Stopping engine talking to peer " + _data.getConfig().getPeer().calculateHash().toBase64());
|
_log.info("Stopping engine talking to peer " + _data.getConfig().getPeer().calculateHash().toBase64());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** start up the test (this does not block, as it fires up the test thread) */
|
/** start up the test (this does not block, as it fires up the test thread) */
|
||||||
public void startEngine() {
|
public void startEngine() {
|
||||||
_active = true;
|
_active = true;
|
||||||
@ -51,17 +52,22 @@ class ClientEngine {
|
|||||||
t.setName("HeartbeatClient " + _id);
|
t.setName("HeartbeatClient " + _id);
|
||||||
t.start();
|
t.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Who are we testing?
|
* Who are we testing?
|
||||||
* @return the Destination (peer) we're testing
|
* @return the Destination (peer) we're testing
|
||||||
*/
|
*/
|
||||||
public Destination getPeer() { return _data.getConfig().getPeer(); }
|
public Destination getPeer() {
|
||||||
|
return _data.getConfig().getPeer();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What is our series identifier (used to locally identify a test)
|
* What is our series identifier (used to locally identify a test)
|
||||||
* @return the series identifier
|
* @return the series identifier
|
||||||
*/
|
*/
|
||||||
public int getSeriesNum() { return _id; }
|
public int getSeriesNum() {
|
||||||
|
return _id;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* receive notification from the heartbeat system that a pong was received in
|
* receive notification from the heartbeat system that a pong was received in
|
||||||
@ -100,23 +106,24 @@ class ClientEngine {
|
|||||||
|
|
||||||
if (Clock.getInstance().now() >= nextSend) {
|
if (Clock.getInstance().now() >= nextSend) {
|
||||||
doSend();
|
doSend();
|
||||||
nextSend = Clock.getInstance().now() + _data.getConfig().getSendFrequency()*1000;
|
nextSend = Clock.getInstance().now() + _data.getConfig().getSendFrequency() * 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Clock.getInstance().now() >= nextWrite) {
|
if (Clock.getInstance().now() >= nextWrite) {
|
||||||
boolean written = writer.persist(_data);
|
boolean written = writer.persist(_data);
|
||||||
if (!written) {
|
if (!written) {
|
||||||
if (_log.shouldLog(Log.ERROR))
|
if (_log.shouldLog(Log.ERROR)) _log.error("Unable to write the client state data");
|
||||||
_log.error("Unable to write the client state data");
|
|
||||||
} else {
|
} else {
|
||||||
if (_log.shouldLog(Log.DEBUG))
|
if (_log.shouldLog(Log.DEBUG)) _log.debug("Client state data written");
|
||||||
_log.debug("Client state data written");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_data.cleanup();
|
_data.cleanup();
|
||||||
|
|
||||||
try { Thread.sleep(1000); } catch (InterruptedException ie) {}
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
} catch (InterruptedException ie) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -83,13 +83,15 @@ public class Heartbeat {
|
|||||||
_adapter = new I2PAdapter();
|
_adapter = new I2PAdapter();
|
||||||
_adapter.setListener(_eventAdapter);
|
_adapter.setListener(_eventAdapter);
|
||||||
}
|
}
|
||||||
private Heartbeat() {}
|
|
||||||
|
private Heartbeat() {
|
||||||
|
}
|
||||||
|
|
||||||
/** load up the config data (but don't build any engines or start them up) */
|
/** load up the config data (but don't build any engines or start them up) */
|
||||||
public void loadConfig() {
|
public void loadConfig() {
|
||||||
Properties props = new Properties();
|
Properties props = new Properties();
|
||||||
FileInputStream fin = null;
|
FileInputStream fin = null;
|
||||||
File configFile = new File (_configFile);
|
File configFile = new File(_configFile);
|
||||||
if (configFile.exists()) {
|
if (configFile.exists()) {
|
||||||
try {
|
try {
|
||||||
fin = new FileInputStream(_configFile);
|
fin = new FileInputStream(_configFile);
|
||||||
@ -99,7 +101,10 @@ public class Heartbeat {
|
|||||||
_log.error("Error reading the config data", ioe);
|
_log.error("Error reading the config data", ioe);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (fin != null) try { fin.close(); } catch (IOException ioe) {}
|
if (fin != null) try {
|
||||||
|
fin.close();
|
||||||
|
} catch (IOException ioe) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -107,7 +112,6 @@ public class Heartbeat {
|
|||||||
loadClientConfigs(props);
|
loadClientConfigs(props);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* send a ping message to the peer
|
* send a ping message to the peer
|
||||||
*
|
*
|
||||||
@ -117,8 +121,7 @@ public class Heartbeat {
|
|||||||
* @param size total message size to send
|
* @param size total message size to send
|
||||||
*/
|
*/
|
||||||
void sendPing(Destination peer, int seriesNum, long now, int size) {
|
void sendPing(Destination peer, int seriesNum, long now, int size) {
|
||||||
if (_adapter.getIsConnected())
|
if (_adapter.getIsConnected()) _adapter.sendPing(peer, seriesNum, now, size);
|
||||||
_adapter.sendPing(peer, seriesNum, now, size);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -148,9 +151,9 @@ public class Heartbeat {
|
|||||||
/** connect to the network */
|
/** connect to the network */
|
||||||
private void connect() {
|
private void connect() {
|
||||||
boolean connected = _adapter.connect();
|
boolean connected = _adapter.connect();
|
||||||
if (!connected)
|
if (!connected) _log.error("Unable to connect to the router");
|
||||||
_log.error("Unable to connect to the router");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** disconnect from the network */
|
/** disconnect from the network */
|
||||||
private void disconnect() {
|
private void disconnect() {
|
||||||
_adapter.disconnect();
|
_adapter.disconnect();
|
||||||
@ -158,8 +161,8 @@ public class Heartbeat {
|
|||||||
|
|
||||||
/** start up all of the tests */
|
/** start up all of the tests */
|
||||||
public void startEngines() {
|
public void startEngines() {
|
||||||
for (Iterator iter = _clientConfigs.values().iterator(); iter.hasNext(); ) {
|
for (Iterator iter = _clientConfigs.values().iterator(); iter.hasNext();) {
|
||||||
ClientConfig config = (ClientConfig)iter.next();
|
ClientConfig config = (ClientConfig) iter.next();
|
||||||
ClientEngine engine = new ClientEngine(this, config);
|
ClientEngine engine = new ClientEngine(this, config);
|
||||||
config.setUs(_adapter.getLocalDestination());
|
config.setUs(_adapter.getLocalDestination());
|
||||||
config.setNumHops(_adapter.getNumHops());
|
config.setNumHops(_adapter.getNumHops());
|
||||||
@ -167,10 +170,11 @@ public class Heartbeat {
|
|||||||
engine.startEngine();
|
engine.startEngine();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** stop all of the tests */
|
/** stop all of the tests */
|
||||||
public void stopEngines() {
|
public void stopEngines() {
|
||||||
for (Iterator iter = _clientEngines.values().iterator(); iter.hasNext(); ) {
|
for (Iterator iter = _clientEngines.values().iterator(); iter.hasNext();) {
|
||||||
ClientEngine engine = (ClientEngine)iter.next();
|
ClientEngine engine = (ClientEngine) iter.next();
|
||||||
engine.stopEngine();
|
engine.stopEngine();
|
||||||
}
|
}
|
||||||
_clientEngines.clear();
|
_clientEngines.clear();
|
||||||
@ -204,7 +208,8 @@ public class Heartbeat {
|
|||||||
synchronized (o) {
|
synchronized (o) {
|
||||||
o.wait();
|
o.wait();
|
||||||
}
|
}
|
||||||
} catch (InterruptedException ie) {}
|
} catch (InterruptedException ie) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -237,7 +242,7 @@ public class Heartbeat {
|
|||||||
* @param data the arbitrary data we sent in the ping (that they sent back in the pong)
|
* @param data the arbitrary data we sent in the ping (that they sent back in the pong)
|
||||||
*/
|
*/
|
||||||
public void receivePong(Destination from, int seriesNum, Date sentOn, Date replyOn, byte[] data) {
|
public void receivePong(Destination from, int seriesNum, Date sentOn, Date replyOn, byte[] data) {
|
||||||
ClientEngine engine = (ClientEngine)_clientEngines.get(new Integer(seriesNum));
|
ClientEngine engine = (ClientEngine) _clientEngines.get(new Integer(seriesNum));
|
||||||
if (engine.getPeer().equals(from)) {
|
if (engine.getPeer().equals(from)) {
|
||||||
engine.receivePong(sentOn.getTime(), replyOn.getTime());
|
engine.receivePong(sentOn.getTime(), replyOn.getTime());
|
||||||
}
|
}
|
||||||
|
@ -84,32 +84,41 @@ class I2PAdapter {
|
|||||||
* who are we?
|
* who are we?
|
||||||
* @return the destination (us)
|
* @return the destination (us)
|
||||||
*/
|
*/
|
||||||
public Destination getLocalDestination() { return _localDest; }
|
public Destination getLocalDestination() {
|
||||||
|
return _localDest;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* who gets notified when we receive a ping or a pong?
|
* who gets notified when we receive a ping or a pong?
|
||||||
* @return the event listener who gets notified
|
* @return the event listener who gets notified
|
||||||
*/
|
*/
|
||||||
public PingPongEventListener getListener() { return _listener; }
|
public PingPongEventListener getListener() {
|
||||||
|
return _listener;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets who gets notified when we receive a ping or a pong
|
* Sets who gets notified when we receive a ping or a pong
|
||||||
* @param listener the event listener to get notified
|
* @param listener the event listener to get notified
|
||||||
*/
|
*/
|
||||||
public void setListener(PingPongEventListener listener) { _listener = listener; }
|
public void setListener(PingPongEventListener listener) {
|
||||||
|
_listener = listener;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* how many hops do we want in our tunnels?
|
* how many hops do we want in our tunnels?
|
||||||
* @return the number of hops
|
* @return the number of hops
|
||||||
*/
|
*/
|
||||||
public int getNumHops() { return _numHops; }
|
public int getNumHops() {
|
||||||
|
return _numHops;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* are we connected?
|
* are we connected?
|
||||||
* @return true or false . . .
|
* @return true or false . . .
|
||||||
*/
|
*/
|
||||||
public boolean getIsConnected() { return _session != null; }
|
public boolean getIsConnected() {
|
||||||
|
return _session != null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read in all of the config data
|
* Read in all of the config data
|
||||||
@ -118,8 +127,8 @@ class I2PAdapter {
|
|||||||
void loadConfig(Properties props) {
|
void loadConfig(Properties props) {
|
||||||
String privDestFile = props.getProperty(DEST_FILE_PROP, DEST_FILE_DEFAULT);
|
String privDestFile = props.getProperty(DEST_FILE_PROP, DEST_FILE_DEFAULT);
|
||||||
String host = props.getProperty(I2CP_HOST_PROP, I2CP_HOST_DEFAULT);
|
String host = props.getProperty(I2CP_HOST_PROP, I2CP_HOST_DEFAULT);
|
||||||
String port = props.getProperty(I2CP_PORT_PROP, ""+I2CP_PORT_DEFAULT);
|
String port = props.getProperty(I2CP_PORT_PROP, "" + I2CP_PORT_DEFAULT);
|
||||||
String numHops = props.getProperty(NUMHOPS_PROP, ""+NUMHOPS_DEFAULT);
|
String numHops = props.getProperty(NUMHOPS_PROP, "" + NUMHOPS_DEFAULT);
|
||||||
|
|
||||||
int portNum = -1;
|
int portNum = -1;
|
||||||
try {
|
try {
|
||||||
@ -164,12 +173,12 @@ class I2PAdapter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (_i2cpPort > 0) {
|
if (_i2cpPort > 0) {
|
||||||
props.setProperty(I2CP_PORT_PROP, ""+_i2cpPort);
|
props.setProperty(I2CP_PORT_PROP, "" + _i2cpPort);
|
||||||
} else {
|
} else {
|
||||||
props.setProperty(I2CP_PORT_PROP, ""+I2CP_PORT_DEFAULT);
|
props.setProperty(I2CP_PORT_PROP, "" + I2CP_PORT_DEFAULT);
|
||||||
}
|
}
|
||||||
|
|
||||||
props.setProperty(NUMHOPS_PROP, ""+_numHops);
|
props.setProperty(NUMHOPS_PROP, "" + _numHops);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final int TYPE_PING = 0;
|
private static final int TYPE_PING = 0;
|
||||||
@ -195,13 +204,14 @@ class I2PAdapter {
|
|||||||
DataHelper.writeDate(baos, new Date(now));
|
DataHelper.writeDate(baos, new Date(now));
|
||||||
int padding = size - baos.size();
|
int padding = size - baos.size();
|
||||||
byte paddingData[] = new byte[padding];
|
byte paddingData[] = new byte[padding];
|
||||||
Arrays.fill(paddingData, (byte)0x2A);
|
Arrays.fill(paddingData, (byte) 0x2A);
|
||||||
DataHelper.writeLong(baos, 2, padding);
|
DataHelper.writeLong(baos, 2, padding);
|
||||||
baos.write(paddingData);
|
baos.write(paddingData);
|
||||||
boolean sent = _session.sendMessage(peer, baos.toByteArray());
|
boolean sent = _session.sendMessage(peer, baos.toByteArray());
|
||||||
if (!sent) {
|
if (!sent) {
|
||||||
if (_log.shouldLog(Log.ERROR)) {
|
if (_log.shouldLog(Log.ERROR)) {
|
||||||
_log.error("Error sending the ping to " + peer.calculateHash().toBase64() + " for series " + seriesNum);
|
_log.error("Error sending the ping to " + peer.calculateHash().toBase64() + " for series "
|
||||||
|
+ seriesNum);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (_log.shouldLog(Log.INFO)) {
|
if (_log.shouldLog(Log.INFO)) {
|
||||||
@ -247,11 +257,13 @@ class I2PAdapter {
|
|||||||
boolean sent = _session.sendMessage(peer, baos.toByteArray());
|
boolean sent = _session.sendMessage(peer, baos.toByteArray());
|
||||||
if (!sent) {
|
if (!sent) {
|
||||||
if (_log.shouldLog(Log.ERROR)) {
|
if (_log.shouldLog(Log.ERROR)) {
|
||||||
_log.error("Error sending the pong to " + peer.calculateHash().toBase64() + " for series " + seriesNum + " which was sent on " + sentOn);
|
_log.error("Error sending the pong to " + peer.calculateHash().toBase64() + " for series "
|
||||||
|
+ seriesNum + " which was sent on " + sentOn);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (_log.shouldLog(Log.INFO)) {
|
if (_log.shouldLog(Log.INFO)) {
|
||||||
_log.info("Pong sent to " + peer.calculateHash().toBase64() + " for series " + seriesNum + " which was sent on " + sentOn);
|
_log.info("Pong sent to " + peer.calculateHash().toBase64() + " for series " + seriesNum
|
||||||
|
+ " which was sent on " + sentOn);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
@ -279,35 +291,37 @@ class I2PAdapter {
|
|||||||
try {
|
try {
|
||||||
Destination from = new Destination();
|
Destination from = new Destination();
|
||||||
from.readBytes(bais);
|
from.readBytes(bais);
|
||||||
int series = (int)DataHelper.readLong(bais, 2);
|
int series = (int) DataHelper.readLong(bais, 2);
|
||||||
long type = DataHelper.readLong(bais, 1);
|
long type = DataHelper.readLong(bais, 1);
|
||||||
Date sentOn = DataHelper.readDate(bais);
|
Date sentOn = DataHelper.readDate(bais);
|
||||||
Date receivedOn = null;
|
Date receivedOn = null;
|
||||||
if (type == TYPE_PONG) {
|
if (type == TYPE_PONG) {
|
||||||
receivedOn = DataHelper.readDate(bais);
|
receivedOn = DataHelper.readDate(bais);
|
||||||
}
|
}
|
||||||
int size = (int)DataHelper.readLong(bais, 2);
|
int size = (int) DataHelper.readLong(bais, 2);
|
||||||
byte payload[] = new byte[size];
|
byte payload[] = new byte[size];
|
||||||
int read = DataHelper.read(bais, payload);
|
int read = DataHelper.read(bais, payload);
|
||||||
if (read != size) {
|
if (read != size) { throw new IOException("Malformed payload - read " + read + " instead of " + size); }
|
||||||
throw new IOException("Malformed payload - read " + read + " instead of " + size);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (_listener == null) {
|
if (_listener == null) {
|
||||||
if (_log.shouldLog(Log.ERROR)) {
|
if (_log.shouldLog(Log.ERROR)) {
|
||||||
_log.error("Listener isn't set, but we received a valid message of type " + type + " sent from " + from.calculateHash().toBase64());
|
_log.error("Listener isn't set, but we received a valid message of type " + type + " sent from "
|
||||||
|
+ from.calculateHash().toBase64());
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type == TYPE_PING) {
|
if (type == TYPE_PING) {
|
||||||
if (_log.shouldLog(Log.INFO)) {
|
if (_log.shouldLog(Log.INFO)) {
|
||||||
_log.info("Ping received from " + from.calculateHash().toBase64() + " on series " + series + " sent on " + sentOn + " containing " + size + " bytes");
|
_log.info("Ping received from " + from.calculateHash().toBase64() + " on series " + series
|
||||||
|
+ " sent on " + sentOn + " containing " + size + " bytes");
|
||||||
}
|
}
|
||||||
_listener.receivePing(from, series, sentOn, payload);
|
_listener.receivePing(from, series, sentOn, payload);
|
||||||
} else if (type == TYPE_PONG) {
|
} else if (type == TYPE_PONG) {
|
||||||
if (_log.shouldLog(Log.INFO)) {
|
if (_log.shouldLog(Log.INFO)) {
|
||||||
_log.info("Pong received from " + from.calculateHash().toBase64() + " on series " + series + " sent on " + sentOn + " with pong sent on " + receivedOn + " containing " + size + " bytes");
|
_log.info("Pong received from " + from.calculateHash().toBase64() + " on series " + series
|
||||||
|
+ " sent on " + sentOn + " with pong sent on " + receivedOn + " containing " + size
|
||||||
|
+ " bytes");
|
||||||
}
|
}
|
||||||
_listener.receivePong(from, series, sentOn, receivedOn, payload);
|
_listener.receivePong(from, series, sentOn, receivedOn, payload);
|
||||||
} else {
|
} else {
|
||||||
@ -325,7 +339,6 @@ class I2PAdapter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* connect to the I2P router and either authenticate ourselves with the
|
* connect to the I2P router and either authenticate ourselves with the
|
||||||
* destination we're given, or create a new one and write that to the
|
* destination we're given, or create a new one and write that to the
|
||||||
@ -366,7 +379,10 @@ class I2PAdapter {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
if (fin != null) try { fin.close(); } catch (IOException ioe) {}
|
if (fin != null) try {
|
||||||
|
fin.close();
|
||||||
|
} catch (IOException ioe) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
@ -391,17 +407,26 @@ class I2PAdapter {
|
|||||||
_log.info("Existing destination loaded: [" + us.toBase64() + "]");
|
_log.info("Existing destination loaded: [" + us.toBase64() + "]");
|
||||||
}
|
}
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
if (fin != null) try { fin.close(); } catch (IOException ioe2) {}
|
if (fin != null) try {
|
||||||
|
fin.close();
|
||||||
|
} catch (IOException ioe2) {
|
||||||
|
}
|
||||||
fin = null;
|
fin = null;
|
||||||
destFile.delete();
|
destFile.delete();
|
||||||
us = null;
|
us = null;
|
||||||
} catch (DataFormatException dfe) {
|
} catch (DataFormatException dfe) {
|
||||||
if (fin != null) try { fin.close(); } catch (IOException ioe2) {}
|
if (fin != null) try {
|
||||||
|
fin.close();
|
||||||
|
} catch (IOException ioe2) {
|
||||||
|
}
|
||||||
fin = null;
|
fin = null;
|
||||||
destFile.delete();
|
destFile.delete();
|
||||||
us = null;
|
us = null;
|
||||||
} finally {
|
} finally {
|
||||||
if (fin != null) try { fin.close(); } catch (IOException ioe2) {}
|
if (fin != null) try {
|
||||||
|
fin.close();
|
||||||
|
} catch (IOException ioe2) {
|
||||||
|
}
|
||||||
fin = null;
|
fin = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -426,7 +451,10 @@ class I2PAdapter {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
} finally {
|
} finally {
|
||||||
if (fos != null) try { fos.close(); } catch (IOException ioe) {}
|
if (fos != null) try {
|
||||||
|
fos.close();
|
||||||
|
} catch (IOException ioe) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return us;
|
return us;
|
||||||
@ -441,8 +469,8 @@ class I2PAdapter {
|
|||||||
props.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_BEST_EFFORT);
|
props.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_BEST_EFFORT);
|
||||||
props.setProperty(I2PClient.PROP_TCP_HOST, _i2cpHost);
|
props.setProperty(I2PClient.PROP_TCP_HOST, _i2cpHost);
|
||||||
props.setProperty(I2PClient.PROP_TCP_PORT, _i2cpPort + "");
|
props.setProperty(I2PClient.PROP_TCP_PORT, _i2cpPort + "");
|
||||||
props.setProperty("tunnels.depthInbound", ""+_numHops);
|
props.setProperty("tunnels.depthInbound", "" + _numHops);
|
||||||
props.setProperty("tunnels.depthOutbound", ""+_numHops);
|
props.setProperty("tunnels.depthOutbound", "" + _numHops);
|
||||||
return props;
|
return props;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -502,19 +530,19 @@ class I2PAdapter {
|
|||||||
}
|
}
|
||||||
disconnect();
|
disconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
/* (non-Javadoc)
|
/* (non-Javadoc)
|
||||||
* @see net.i2p.client.I2PSessionListener#errorOccurred(net.i2p.client.I2PSession, java.lang.String, java.lang.Throwable)
|
* @see net.i2p.client.I2PSessionListener#errorOccurred(net.i2p.client.I2PSession, java.lang.String, java.lang.Throwable)
|
||||||
*/
|
*/
|
||||||
public void errorOccurred(I2PSession session, String message, Throwable error) {
|
public void errorOccurred(I2PSession session, String message, Throwable error) {
|
||||||
if (_log.shouldLog(Log.ERROR))
|
if (_log.shouldLog(Log.ERROR)) _log.error("Error occurred", error);
|
||||||
_log.error("Error occurred", error);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* (non-Javadoc)
|
/* (non-Javadoc)
|
||||||
* @see net.i2p.client.I2PSessionListener#reportAbuse(net.i2p.client.I2PSession, int)
|
* @see net.i2p.client.I2PSessionListener#reportAbuse(net.i2p.client.I2PSession, int)
|
||||||
*/
|
*/
|
||||||
public void reportAbuse(I2PSession session, int severity) {
|
public void reportAbuse(I2PSession session, int severity) {
|
||||||
if (_log.shouldLog(Log.ERROR))
|
if (_log.shouldLog(Log.ERROR)) _log.error("Abuse reported");
|
||||||
_log.error("Abuse reported");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* (non-Javadoc)
|
/* (non-Javadoc)
|
||||||
@ -525,8 +553,7 @@ class I2PAdapter {
|
|||||||
byte data[] = session.receiveMessage(msgId);
|
byte data[] = session.receiveMessage(msgId);
|
||||||
handleMessage(data);
|
handleMessage(data);
|
||||||
} catch (I2PSessionException ise) {
|
} catch (I2PSessionException ise) {
|
||||||
if (_log.shouldLog(Log.ERROR))
|
if (_log.shouldLog(Log.ERROR)) _log.error("Error receiving the message", ise);
|
||||||
_log.error("Error receiving the message", ise);
|
|
||||||
disconnect();
|
disconnect();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -37,7 +37,7 @@ public class PeerData {
|
|||||||
private RateStat _lostRate;
|
private RateStat _lostRate;
|
||||||
|
|
||||||
/** how long we wait before timing out pending pings (30 seconds) */
|
/** how long we wait before timing out pending pings (30 seconds) */
|
||||||
private static final long TIMEOUT_PERIOD = 30*1000;
|
private static final long TIMEOUT_PERIOD = 30 * 1000;
|
||||||
|
|
||||||
/** synchronize on this when updating _dataPoints or _pendingPings */
|
/** synchronize on this when updating _dataPoints or _pendingPings */
|
||||||
private Object _updateLock = new Object();
|
private Object _updateLock = new Object();
|
||||||
@ -53,9 +53,12 @@ public class PeerData {
|
|||||||
_sessionStart = Clock.getInstance().now();
|
_sessionStart = Clock.getInstance().now();
|
||||||
_lifetimeSent = 0;
|
_lifetimeSent = 0;
|
||||||
_lifetimeReceived = 0;
|
_lifetimeReceived = 0;
|
||||||
_sendRate = new RateStat("sendRate", "How long it takes to send", "peer", getPeriods(config.getAveragePeriods()));
|
_sendRate = new RateStat("sendRate", "How long it takes to send", "peer",
|
||||||
_receiveRate = new RateStat("receiveRate", "How long it takes to receive", "peer", getPeriods(config.getAveragePeriods()));
|
getPeriods(config.getAveragePeriods()));
|
||||||
_lostRate = new RateStat("lostRate", "How frequently we lose messages", "peer", getPeriods(config.getAveragePeriods()));
|
_receiveRate = new RateStat("receiveRate", "How long it takes to receive", "peer",
|
||||||
|
getPeriods(config.getAveragePeriods()));
|
||||||
|
_lostRate = new RateStat("lostRate", "How frequently we lose messages", "peer",
|
||||||
|
getPeriods(config.getAveragePeriods()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -68,7 +71,7 @@ public class PeerData {
|
|||||||
if (periods == null) periods = new int[0];
|
if (periods == null) periods = new int[0];
|
||||||
rv = new long[periods.length];
|
rv = new long[periods.length];
|
||||||
for (int i = 0; i < periods.length; i++)
|
for (int i = 0; i < periods.length; i++)
|
||||||
rv[i] = (long)periods[i] * 60*1000; // they're in minutes
|
rv[i] = (long) periods[i] * 60 * 1000; // they're in minutes
|
||||||
Arrays.sort(rv);
|
Arrays.sort(rv);
|
||||||
return rv;
|
return rv;
|
||||||
}
|
}
|
||||||
@ -77,43 +80,60 @@ public class PeerData {
|
|||||||
* how many pings are still outstanding?
|
* how many pings are still outstanding?
|
||||||
* @return the number of pings outstanding
|
* @return the number of pings outstanding
|
||||||
*/
|
*/
|
||||||
public int getPendingCount() { synchronized (_updateLock) { return _pendingPings.size(); } }
|
public int getPendingCount() {
|
||||||
|
synchronized (_updateLock) {
|
||||||
|
return _pendingPings.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* how many data points are available in the current window?
|
* how many data points are available in the current window?
|
||||||
* @return the number of datapoints available
|
* @return the number of datapoints available
|
||||||
*/
|
*/
|
||||||
public int getDataPointCount() { synchronized (_updateLock) { return _dataPoints.size(); } }
|
public int getDataPointCount() {
|
||||||
|
synchronized (_updateLock) {
|
||||||
|
return _dataPoints.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* when did this test begin?
|
* when did this test begin?
|
||||||
* @return when the test began
|
* @return when the test began
|
||||||
*/
|
*/
|
||||||
public long getSessionStart() { return _sessionStart; }
|
public long getSessionStart() {
|
||||||
|
return _sessionStart;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* how many pings have we sent for this test?
|
* how many pings have we sent for this test?
|
||||||
* @return the number of pings sent
|
* @return the number of pings sent
|
||||||
*/
|
*/
|
||||||
public long getLifetimeSent() { return _lifetimeSent; }
|
public long getLifetimeSent() {
|
||||||
|
return _lifetimeSent;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* how many pongs have we received for this test?
|
* how many pongs have we received for this test?
|
||||||
* @return the number of pings received
|
* @return the number of pings received
|
||||||
*/
|
*/
|
||||||
public long getLifetimeReceived() { return _lifetimeReceived; }
|
public long getLifetimeReceived() {
|
||||||
|
return _lifetimeReceived;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return the client configuration
|
* @return the client configuration
|
||||||
*/
|
*/
|
||||||
public ClientConfig getConfig() { return _peer; }
|
public ClientConfig getConfig() {
|
||||||
|
return _peer;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What periods are we averaging the data over (in minutes)?
|
* What periods are we averaging the data over (in minutes)?
|
||||||
* @return the periods as an array of ints (in minutes)
|
* @return the periods as an array of ints (in minutes)
|
||||||
*/
|
*/
|
||||||
public int[] getAveragePeriods() { return (_peer.getAveragePeriods() != null ? _peer.getAveragePeriods() : new int[0]); }
|
public int[] getAveragePeriods() {
|
||||||
|
return (_peer.getAveragePeriods() != null ? _peer.getAveragePeriods() : new int[0]);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* average time to send over the given period.
|
* average time to send over the given period.
|
||||||
@ -121,7 +141,9 @@ public class PeerData {
|
|||||||
* @param period number of minutes to retrieve the average for
|
* @param period number of minutes to retrieve the average for
|
||||||
* @return milliseconds average, or -1 if we dont track that period
|
* @return milliseconds average, or -1 if we dont track that period
|
||||||
*/
|
*/
|
||||||
public double getAverageSendTime(int period) { return getAverage(_sendRate, period); }
|
public double getAverageSendTime(int period) {
|
||||||
|
return getAverage(_sendRate, period);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* average time to receive over the given period.
|
* average time to receive over the given period.
|
||||||
@ -129,7 +151,9 @@ public class PeerData {
|
|||||||
* @param period number of minutes to retrieve the average for
|
* @param period number of minutes to retrieve the average for
|
||||||
* @return milliseconds average, or -1 if we dont track that period
|
* @return milliseconds average, or -1 if we dont track that period
|
||||||
*/
|
*/
|
||||||
public double getAverageReceiveTime(int period) { return getAverage(_receiveRate, period); }
|
public double getAverageReceiveTime(int period) {
|
||||||
|
return getAverage(_receiveRate, period);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* number of lost messages over the given period.
|
* number of lost messages over the given period.
|
||||||
@ -138,16 +162,14 @@ public class PeerData {
|
|||||||
* @return number of lost messages in the period, or -1 if we dont track that period
|
* @return number of lost messages in the period, or -1 if we dont track that period
|
||||||
*/
|
*/
|
||||||
public double getLostMessages(int period) {
|
public double getLostMessages(int period) {
|
||||||
Rate rate = _lostRate.getRate(period * 60*1000);
|
Rate rate = _lostRate.getRate(period * 60 * 1000);
|
||||||
if (rate == null)
|
if (rate == null) return -1;
|
||||||
return -1;
|
|
||||||
return rate.getCurrentTotalValue();
|
return rate.getCurrentTotalValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
private double getAverage(RateStat stat, int period) {
|
private double getAverage(RateStat stat, int period) {
|
||||||
Rate rate = stat.getRate(period * 60*1000);
|
Rate rate = stat.getRate(period * 60 * 1000);
|
||||||
if (rate == null)
|
if (rate == null) return -1;
|
||||||
return -1;
|
|
||||||
return rate.getAverageValue();
|
return rate.getAverageValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -184,7 +206,7 @@ public class PeerData {
|
|||||||
public void pongReceived(long dateSent, long pongSent) {
|
public void pongReceived(long dateSent, long pongSent) {
|
||||||
long now = Clock.getInstance().now();
|
long now = Clock.getInstance().now();
|
||||||
synchronized (_updateLock) {
|
synchronized (_updateLock) {
|
||||||
EventDataPoint data = (EventDataPoint)_pendingPings.remove(new Long(dateSent));
|
EventDataPoint data = (EventDataPoint) _pendingPings.remove(new Long(dateSent));
|
||||||
if (data != null) {
|
if (data != null) {
|
||||||
data.setPongReceived(now);
|
data.setPongReceived(now);
|
||||||
data.setPongSent(pongSent);
|
data.setPongSent(pongSent);
|
||||||
@ -192,8 +214,8 @@ public class PeerData {
|
|||||||
_dataPoints.put(new Long(dateSent), data);
|
_dataPoints.put(new Long(dateSent), data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_sendRate.addData(pongSent-dateSent, 0);
|
_sendRate.addData(pongSent - dateSent, 0);
|
||||||
_receiveRate.addData(now-pongSent, 0);
|
_receiveRate.addData(now - pongSent, 0);
|
||||||
_lifetimeReceived++;
|
_lifetimeReceived++;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -204,7 +226,7 @@ public class PeerData {
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public void cleanup() {
|
public void cleanup() {
|
||||||
long dropBefore = Clock.getInstance().now() - _peer.getStatDuration() * 60*1000;
|
long dropBefore = Clock.getInstance().now() - _peer.getStatDuration() * 60 * 1000;
|
||||||
long timeoutBefore = Clock.getInstance().now() - TIMEOUT_PERIOD;
|
long timeoutBefore = Clock.getInstance().now() - TIMEOUT_PERIOD;
|
||||||
long numDropped = 0;
|
long numDropped = 0;
|
||||||
long numTimedOut = 0;
|
long numTimedOut = 0;
|
||||||
@ -212,8 +234,8 @@ public class PeerData {
|
|||||||
synchronized (_updateLock) {
|
synchronized (_updateLock) {
|
||||||
List toTimeout = new ArrayList(4);
|
List toTimeout = new ArrayList(4);
|
||||||
List toDrop = new ArrayList(4);
|
List toDrop = new ArrayList(4);
|
||||||
for (Iterator iter = _pendingPings.keySet().iterator(); iter.hasNext(); ) {
|
for (Iterator iter = _pendingPings.keySet().iterator(); iter.hasNext();) {
|
||||||
Long when = (Long)iter.next();
|
Long when = (Long) iter.next();
|
||||||
if (when.longValue() < dropBefore)
|
if (when.longValue() < dropBefore)
|
||||||
toDrop.add(when);
|
toDrop.add(when);
|
||||||
else if (when.longValue() < timeoutBefore)
|
else if (when.longValue() < timeoutBefore)
|
||||||
@ -221,14 +243,14 @@ public class PeerData {
|
|||||||
else
|
else
|
||||||
break; // its ordered, so once we are past timeoutBefore, no need
|
break; // its ordered, so once we are past timeoutBefore, no need
|
||||||
}
|
}
|
||||||
for (Iterator iter = toDrop.iterator(); iter.hasNext(); ) {
|
for (Iterator iter = toDrop.iterator(); iter.hasNext();) {
|
||||||
_pendingPings.remove(iter.next());
|
_pendingPings.remove(iter.next());
|
||||||
}
|
}
|
||||||
|
|
||||||
List toAdd = new ArrayList(toTimeout.size());
|
List toAdd = new ArrayList(toTimeout.size());
|
||||||
for (Iterator iter = toTimeout.iterator(); iter.hasNext(); ) {
|
for (Iterator iter = toTimeout.iterator(); iter.hasNext();) {
|
||||||
Long when = (Long)iter.next();
|
Long when = (Long) iter.next();
|
||||||
EventDataPoint data = (EventDataPoint)_pendingPings.remove(when);
|
EventDataPoint data = (EventDataPoint) _pendingPings.remove(when);
|
||||||
data.setWasPonged(false);
|
data.setWasPonged(false);
|
||||||
toAdd.add(data);
|
toAdd.add(data);
|
||||||
}
|
}
|
||||||
@ -237,21 +259,21 @@ public class PeerData {
|
|||||||
numTimedOut = toDrop.size();
|
numTimedOut = toDrop.size();
|
||||||
toDrop.clear();
|
toDrop.clear();
|
||||||
|
|
||||||
for (Iterator iter = _dataPoints.keySet().iterator(); iter.hasNext(); ) {
|
for (Iterator iter = _dataPoints.keySet().iterator(); iter.hasNext();) {
|
||||||
Long when = (Long)iter.next();
|
Long when = (Long) iter.next();
|
||||||
if (when.longValue() < dropBefore)
|
if (when.longValue() < dropBefore)
|
||||||
toDrop.add(when);
|
toDrop.add(when);
|
||||||
else
|
else
|
||||||
break; // ordered
|
break; // ordered
|
||||||
}
|
}
|
||||||
for (Iterator iter = toDrop.iterator(); iter.hasNext(); ) {
|
for (Iterator iter = toDrop.iterator(); iter.hasNext();) {
|
||||||
_dataPoints.remove(iter.next());
|
_dataPoints.remove(iter.next());
|
||||||
}
|
}
|
||||||
|
|
||||||
numDropped += toDrop.size();
|
numDropped += toDrop.size();
|
||||||
|
|
||||||
for (Iterator iter = toAdd.iterator(); iter.hasNext(); ) {
|
for (Iterator iter = toAdd.iterator(); iter.hasNext();) {
|
||||||
EventDataPoint data = (EventDataPoint)iter.next();
|
EventDataPoint data = (EventDataPoint) iter.next();
|
||||||
_dataPoints.put(new Long(data.getPingSent()), data);
|
_dataPoints.put(new Long(data.getPingSent()), data);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -265,7 +287,8 @@ public class PeerData {
|
|||||||
_lostRate.coallesceStats();
|
_lostRate.coallesceStats();
|
||||||
|
|
||||||
if (_log.shouldLog(Log.DEBUG))
|
if (_log.shouldLog(Log.DEBUG))
|
||||||
_log.debug("Peer data cleaned up " + numTimedOut + " timed out pings and removed " + numDropped + " old entries");
|
_log.debug("Peer data cleaned up " + numTimedOut + " timed out pings and removed " + numDropped
|
||||||
|
+ " old entries");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** actual data point for the peer */
|
/** actual data point for the peer */
|
||||||
@ -297,47 +320,63 @@ public class PeerData {
|
|||||||
* when did we send this ping?
|
* when did we send this ping?
|
||||||
* @return the time the ping was sent
|
* @return the time the ping was sent
|
||||||
*/
|
*/
|
||||||
public long getPingSent() { return _pingSent; }
|
public long getPingSent() {
|
||||||
|
return _pingSent;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the time the ping was sent
|
* Set the time the ping was sent
|
||||||
* @param when time to set
|
* @param when time to set
|
||||||
*/
|
*/
|
||||||
public void setPingSent(long when) { _pingSent = when; }
|
public void setPingSent(long when) {
|
||||||
|
_pingSent = when;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* when did the peer receive the ping?
|
* when did the peer receive the ping?
|
||||||
* @return the time the ping was receieved
|
* @return the time the ping was receieved
|
||||||
*/
|
*/
|
||||||
public long getPongSent() { return _pongSent; }
|
public long getPongSent() {
|
||||||
|
return _pongSent;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the time the peer received the ping
|
* Set the time the peer received the ping
|
||||||
* @param when the time to set
|
* @param when the time to set
|
||||||
*/
|
*/
|
||||||
public void setPongSent(long when) { _pongSent = when; }
|
public void setPongSent(long when) {
|
||||||
|
_pongSent = when;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* when did we receive the peer's pong?
|
* when did we receive the peer's pong?
|
||||||
* @return the time we receieved the pong
|
* @return the time we receieved the pong
|
||||||
*/
|
*/
|
||||||
public long getPongReceived() { return _pongReceived; }
|
public long getPongReceived() {
|
||||||
|
return _pongReceived;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the time the peer's pong was receieved
|
* Set the time the peer's pong was receieved
|
||||||
* @param when the time to set
|
* @param when the time to set
|
||||||
*/
|
*/
|
||||||
public void setPongReceived(long when) { _pongReceived = when; }
|
public void setPongReceived(long when) {
|
||||||
|
_pongReceived = when;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* did the peer reply in time?
|
* did the peer reply in time?
|
||||||
* @return true or false, whether we got a reply in time */
|
* @return true or false, whether we got a reply in time */
|
||||||
public boolean getWasPonged() { return _wasPonged; }
|
public boolean getWasPonged() {
|
||||||
|
return _wasPonged;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set whether we receieved the peer's reply in time
|
* Set whether we receieved the peer's reply in time
|
||||||
* @param pong true or false
|
* @param pong true or false
|
||||||
*/
|
*/
|
||||||
public void setWasPonged(boolean pong) { _wasPonged = pong; }
|
public void setWasPonged(boolean pong) {
|
||||||
|
_wasPonged = pong;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -35,17 +35,21 @@ class PeerDataWriter {
|
|||||||
fos = new FileOutputStream(statFile);
|
fos = new FileOutputStream(statFile);
|
||||||
fos.write(header.getBytes());
|
fos.write(header.getBytes());
|
||||||
fos.write("#action\tstatus\tdate and time sent \tsendMs\treplyMs\n".getBytes());
|
fos.write("#action\tstatus\tdate and time sent \tsendMs\treplyMs\n".getBytes());
|
||||||
for (Iterator iter = data.getDataPoints().iterator(); iter.hasNext(); ) {
|
for (Iterator iter = data.getDataPoints().iterator(); iter.hasNext();) {
|
||||||
PeerData.EventDataPoint point = (PeerData.EventDataPoint)iter.next();
|
PeerData.EventDataPoint point = (PeerData.EventDataPoint) iter.next();
|
||||||
String line = getEvent(point);
|
String line = getEvent(point);
|
||||||
fos.write(line.getBytes());
|
fos.write(line.getBytes());
|
||||||
}
|
}
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
if (_log.shouldLog(Log.ERROR))
|
if (_log.shouldLog(Log.ERROR))
|
||||||
_log.error("Error persisting the peer data for " + data.getConfig().getPeer().calculateHash().toBase64(), ioe);
|
_log.error("Error persisting the peer data for "
|
||||||
|
+ data.getConfig().getPeer().calculateHash().toBase64(), ioe);
|
||||||
return false;
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
if (fos != null) try { fos.close(); } catch (IOException ioe) {}
|
if (fos != null) try {
|
||||||
|
fos.close();
|
||||||
|
} catch (IOException ioe) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -16,6 +16,7 @@ class PeerPlotConfig {
|
|||||||
}
|
}
|
||||||
// baf
|
// baf
|
||||||
}
|
}
|
||||||
|
|
||||||
// moo
|
// moo
|
||||||
|
|
||||||
private final static void biff() {
|
private final static void biff() {
|
||||||
|
@ -28,8 +28,7 @@ public class HTTPListener extends Thread {
|
|||||||
* @param listenHost A host, to connect to.
|
* @param listenHost A host, to connect to.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
public HTTPListener(SocketManagerProducer smp, int port,
|
public HTTPListener(SocketManagerProducer smp, int port, String listenHost) {
|
||||||
String listenHost) {
|
|
||||||
this.smp = smp;
|
this.smp = smp;
|
||||||
this.port = port;
|
this.port = port;
|
||||||
start();
|
start();
|
||||||
@ -40,11 +39,9 @@ public class HTTPListener extends Thread {
|
|||||||
*/
|
*/
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
InetAddress lh = listenHost == null
|
InetAddress lh = listenHost == null ? null : InetAddress.getByName(listenHost);
|
||||||
? null
|
|
||||||
: InetAddress.getByName(listenHost);
|
|
||||||
ServerSocket ss = new ServerSocket(port, 0, lh);
|
ServerSocket ss = new ServerSocket(port, 0, lh);
|
||||||
while(true) {
|
while (true) {
|
||||||
Socket s = ss.accept();
|
Socket s = ss.accept();
|
||||||
new HTTPSocketHandler(this, s);
|
new HTTPSocketHandler(this, s);
|
||||||
}
|
}
|
||||||
@ -53,7 +50,7 @@ public class HTTPListener extends Thread {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean proxyUsed=false;
|
private boolean proxyUsed = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query whether this is the first use of the proxy or not . . .
|
* Query whether this is the first use of the proxy or not . . .
|
||||||
@ -65,7 +62,7 @@ public class HTTPListener extends Thread {
|
|||||||
if (proxyUsed) {
|
if (proxyUsed) {
|
||||||
return false;
|
return false;
|
||||||
} else {
|
} else {
|
||||||
proxyUsed=true;
|
proxyUsed = true;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -84,8 +81,7 @@ public class HTTPListener extends Thread {
|
|||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
public void handleNotImplemented(OutputStream out) throws IOException {
|
public void handleNotImplemented(OutputStream out) throws IOException {
|
||||||
out.write(("HTTP/1.1 200 Document following\n\n"+
|
out.write(("HTTP/1.1 200 Document following\n\n" + "<h1>Feature not implemented</h1>").getBytes("ISO-8859-1"));
|
||||||
"<h1>Feature not implemented</h1>").getBytes("ISO-8859-1"));
|
|
||||||
out.flush();
|
out.flush();
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -28,12 +28,11 @@ public class HTTPSocketHandler extends Thread {
|
|||||||
*/
|
*/
|
||||||
public HTTPSocketHandler(HTTPListener httpl, Socket s) {
|
public HTTPSocketHandler(HTTPListener httpl, Socket s) {
|
||||||
this.httpl = httpl;
|
this.httpl = httpl;
|
||||||
this.s=s;
|
this.s = s;
|
||||||
h = RootHandler.getInstance();
|
h = RootHandler.getInstance();
|
||||||
start();
|
start();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* (non-Javadoc)
|
/* (non-Javadoc)
|
||||||
* @see java.lang.Thread#run()
|
* @see java.lang.Thread#run()
|
||||||
*/
|
*/
|
||||||
|
@ -44,10 +44,9 @@ public class HTTPTunnel {
|
|||||||
* @param shouldThrowAwayManagers whether to throw away a manager after use
|
* @param shouldThrowAwayManagers whether to throw away a manager after use
|
||||||
* @param listenPort which port to listen on
|
* @param listenPort which port to listen on
|
||||||
*/
|
*/
|
||||||
public HTTPTunnel(I2PSocketManager[] initialManagers, int maxManagers,
|
public HTTPTunnel(I2PSocketManager[] initialManagers, int maxManagers, boolean shouldThrowAwayManagers,
|
||||||
boolean shouldThrowAwayManagers, int listenPort) {
|
int listenPort) {
|
||||||
this(initialManagers, maxManagers, shouldThrowAwayManagers, listenPort,
|
this(initialManagers, maxManagers, shouldThrowAwayManagers, listenPort, "127.0.0.1", 7654);
|
||||||
"127.0.0.1", 7654);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -60,12 +59,10 @@ public class HTTPTunnel {
|
|||||||
* @param i2cpAddress the I2CP address
|
* @param i2cpAddress the I2CP address
|
||||||
* @param i2cpPort the I2CP port
|
* @param i2cpPort the I2CP port
|
||||||
*/
|
*/
|
||||||
public HTTPTunnel(I2PSocketManager[] initialManagers, int maxManagers,
|
public HTTPTunnel(I2PSocketManager[] initialManagers, int maxManagers, boolean shouldThrowAwayManagers,
|
||||||
boolean shouldThrowAwayManagers, int listenPort,
|
int listenPort, String i2cpAddress, int i2cpPort) {
|
||||||
String i2cpAddress, int i2cpPort) {
|
SocketManagerProducer smp = new SocketManagerProducer(initialManagers, maxManagers, shouldThrowAwayManagers,
|
||||||
SocketManagerProducer smp =
|
i2cpAddress, i2cpPort);
|
||||||
new SocketManagerProducer(initialManagers, maxManagers,
|
|
||||||
shouldThrowAwayManagers, i2cpAddress, i2cpPort);
|
|
||||||
new HTTPListener(smp, listenPort, "127.0.0.1");
|
new HTTPListener(smp, listenPort, "127.0.0.1");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -78,20 +75,22 @@ public class HTTPTunnel {
|
|||||||
String host = "127.0.0.1";
|
String host = "127.0.0.1";
|
||||||
int port = 7654, max = 1;
|
int port = 7654, max = 1;
|
||||||
boolean throwAwayManagers = false;
|
boolean throwAwayManagers = false;
|
||||||
if (args.length >1) {
|
if (args.length > 1) {
|
||||||
if (args.length == 4) {
|
if (args.length == 4) {
|
||||||
host = args[2];
|
host = args[2];
|
||||||
port = Integer.parseInt(args[3]);
|
port = Integer.parseInt(args[3]);
|
||||||
} else if (args.length != 2) {
|
} else if (args.length != 2) {
|
||||||
showInfo(); return;
|
showInfo();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
max = Integer.parseInt(args[1]);
|
max = Integer.parseInt(args[1]);
|
||||||
} else if (args.length != 1) {
|
} else if (args.length != 1) {
|
||||||
showInfo(); return;
|
showInfo();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
if (max == 0) {
|
if (max == 0) {
|
||||||
max = 1;
|
max = 1;
|
||||||
} else if (max <0) {
|
} else if (max < 0) {
|
||||||
max = -max;
|
max = -max;
|
||||||
throwAwayManagers = true;
|
throwAwayManagers = true;
|
||||||
}
|
}
|
||||||
@ -99,17 +98,11 @@ public class HTTPTunnel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static void showInfo() {
|
private static void showInfo() {
|
||||||
System.out.println
|
System.out.println("Usage: java HTTPTunnel <listenPort> [<max> " + "[<i2cphost> <i2cpport>]]\n"
|
||||||
("Usage: java HTTPTunnel <listenPort> [<max> "+
|
+ " <listenPort> port to listen for browsers\n"
|
||||||
"[<i2cphost> <i2cpport>]]\n"+
|
+ " <max> max number of SocketMangers in pool, " + "use neg. number\n"
|
||||||
" <listenPort> port to listen for browsers\n"+
|
+ " to use each SocketManager only once " + "(default: 1)\n"
|
||||||
" <max> max number of SocketMangers in pool, "+
|
+ " <i2cphost> host to connect to the router " + "(default: 127.0.0.1)\n"
|
||||||
"use neg. number\n"+
|
+ " <i2cpport> port to connect to the router " + "(default: 7654)");
|
||||||
" to use each SocketManager only once "+
|
|
||||||
"(default: 1)\n"+
|
|
||||||
" <i2cphost> host to connect to the router "+
|
|
||||||
"(default: 127.0.0.1)\n"+
|
|
||||||
" <i2cpport> port to connect to the router "+
|
|
||||||
"(default: 7654)");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -29,8 +29,7 @@ public class Request {
|
|||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
public Request(InputStream in) throws IOException {
|
public Request(InputStream in) throws IOException {
|
||||||
BufferedReader br = new BufferedReader
|
BufferedReader br = new BufferedReader(new InputStreamReader(in, "ISO-8859-1"));
|
||||||
(new InputStreamReader(in, "ISO-8859-1"));
|
|
||||||
String line = br.readLine();
|
String line = br.readLine();
|
||||||
if (line == null) { // no data at all
|
if (line == null) { // no data at all
|
||||||
method = null;
|
method = null;
|
||||||
@ -40,20 +39,20 @@ public class Request {
|
|||||||
int pos = line.indexOf(" ");
|
int pos = line.indexOf(" ");
|
||||||
if (pos == -1) {
|
if (pos == -1) {
|
||||||
method = line;
|
method = line;
|
||||||
url="";
|
url = "";
|
||||||
_log.error("Malformed HTTP request: "+line);
|
_log.error("Malformed HTTP request: " + line);
|
||||||
} else {
|
} else {
|
||||||
method = line.substring(0,pos);
|
method = line.substring(0, pos);
|
||||||
url=line.substring(pos+1);
|
url = line.substring(pos + 1);
|
||||||
}
|
}
|
||||||
proto="";
|
proto = "";
|
||||||
pos = url.indexOf(" ");
|
pos = url.indexOf(" ");
|
||||||
if (pos != -1) {
|
if (pos != -1) {
|
||||||
proto=url.substring(pos); // leading space intended
|
proto = url.substring(pos); // leading space intended
|
||||||
url = url.substring(0,pos);
|
url = url.substring(0, pos);
|
||||||
}
|
}
|
||||||
StringBuffer sb = new StringBuffer(512);
|
StringBuffer sb = new StringBuffer(512);
|
||||||
while((line=br.readLine()) != null) {
|
while ((line = br.readLine()) != null) {
|
||||||
if (line.length() == 0) break;
|
if (line.length() == 0) break;
|
||||||
sb.append(line).append("\r\n");
|
sb.append(line).append("\r\n");
|
||||||
}
|
}
|
||||||
@ -64,14 +63,14 @@ public class Request {
|
|||||||
// FIXME: do this better, please.
|
// FIXME: do this better, please.
|
||||||
if (!method.equals("GET")) {
|
if (!method.equals("GET")) {
|
||||||
while (br.ready()) { // empty the buffer (POST requests)
|
while (br.ready()) { // empty the buffer (POST requests)
|
||||||
int i=br.read();
|
int i = br.read();
|
||||||
if (i != -1) {
|
if (i != -1) {
|
||||||
sb.append((char)i);
|
sb.append((char) i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
postData = sb.toString();
|
postData = sb.toString();
|
||||||
} else {
|
} else {
|
||||||
postData="";
|
postData = "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -87,7 +86,7 @@ public class Request {
|
|||||||
|
|
||||||
private String toISO8859_1String() throws IOException {
|
private String toISO8859_1String() throws IOException {
|
||||||
if (method == null) return null;
|
if (method == null) return null;
|
||||||
return method+" "+url+proto+"\r\n"+params+"\r\n"+postData;
|
return method + " " + url + proto + "\r\n" + params + "\r\n" + postData;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -102,7 +101,7 @@ public class Request {
|
|||||||
* @param newURL the new URL
|
* @param newURL the new URL
|
||||||
*/
|
*/
|
||||||
public void setURL(String newURL) {
|
public void setURL(String newURL) {
|
||||||
url=newURL;
|
url = newURL;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -112,12 +111,10 @@ public class Request {
|
|||||||
*/
|
*/
|
||||||
public String getParam(String name) {
|
public String getParam(String name) {
|
||||||
try {
|
try {
|
||||||
BufferedReader br= new BufferedReader(new StringReader(params));
|
BufferedReader br = new BufferedReader(new StringReader(params));
|
||||||
String line;
|
String line;
|
||||||
while ((line = br.readLine()) != null) {
|
while ((line = br.readLine()) != null) {
|
||||||
if (line.startsWith(name)) {
|
if (line.startsWith(name)) { return line.substring(name.length()); }
|
||||||
return line.substring(name.length());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
@ -133,22 +130,22 @@ public class Request {
|
|||||||
*/
|
*/
|
||||||
public void setParam(String name, String value) {
|
public void setParam(String name, String value) {
|
||||||
try {
|
try {
|
||||||
StringBuffer sb = new StringBuffer(params.length()+value.length());
|
StringBuffer sb = new StringBuffer(params.length() + value.length());
|
||||||
BufferedReader br= new BufferedReader(new StringReader(params));
|
BufferedReader br = new BufferedReader(new StringReader(params));
|
||||||
String line;
|
String line;
|
||||||
boolean replaced = false;
|
boolean replaced = false;
|
||||||
while((line=br.readLine()) != null) {
|
while ((line = br.readLine()) != null) {
|
||||||
if (line.startsWith(name)) {
|
if (line.startsWith(name)) {
|
||||||
replaced=true;
|
replaced = true;
|
||||||
if (value == null) continue; // kill param
|
if (value == null) continue; // kill param
|
||||||
line = name+value;
|
line = name + value;
|
||||||
}
|
}
|
||||||
sb.append(line).append("\r\n");
|
sb.append(line).append("\r\n");
|
||||||
}
|
}
|
||||||
if (!replaced && value != null) {
|
if (!replaced && value != null) {
|
||||||
sb.append(name).append(value).append("\r\n");
|
sb.append(name).append(value).append("\r\n");
|
||||||
}
|
}
|
||||||
params=sb.toString();
|
params = sb.toString();
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
_log.error("Error getting parameter", ex);
|
_log.error("Error getting parameter", ex);
|
||||||
}
|
}
|
||||||
|
@ -29,32 +29,27 @@ public class SocketManagerProducer extends Thread {
|
|||||||
* @param host which host to listen on
|
* @param host which host to listen on
|
||||||
* @param port which port to listen on
|
* @param port which port to listen on
|
||||||
*/
|
*/
|
||||||
public SocketManagerProducer(I2PSocketManager[] initialManagers,
|
public SocketManagerProducer(I2PSocketManager[] initialManagers, int maxManagers, boolean shouldThrowAwayManagers,
|
||||||
int maxManagers,
|
|
||||||
boolean shouldThrowAwayManagers,
|
|
||||||
String host, int port) {
|
String host, int port) {
|
||||||
if (maxManagers < 1) {
|
if (maxManagers < 1) { throw new IllegalArgumentException("maxManagers < 1"); }
|
||||||
throw new IllegalArgumentException("maxManagers < 1");
|
this.host = host;
|
||||||
}
|
this.port = port;
|
||||||
this.host=host;
|
this.shouldThrowAwayManagers = shouldThrowAwayManagers;
|
||||||
this.port=port;
|
|
||||||
this.shouldThrowAwayManagers=shouldThrowAwayManagers;
|
|
||||||
if (initialManagers != null) {
|
if (initialManagers != null) {
|
||||||
myManagers.addAll(Arrays.asList(initialManagers));
|
myManagers.addAll(Arrays.asList(initialManagers));
|
||||||
}
|
}
|
||||||
this.maxManagers=maxManagers;
|
this.maxManagers = maxManagers;
|
||||||
this.shouldThrowAwayManagers=shouldThrowAwayManagers;
|
this.shouldThrowAwayManagers = shouldThrowAwayManagers;
|
||||||
setDaemon(true);
|
setDaemon(true);
|
||||||
start();
|
start();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Thread producing new SocketManagers.
|
* Thread producing new SocketManagers.
|
||||||
*/
|
*/
|
||||||
public void run() {
|
public void run() {
|
||||||
while (true) {
|
while (true) {
|
||||||
synchronized(this) {
|
synchronized (this) {
|
||||||
// without mcDonalds mode, we most probably need no
|
// without mcDonalds mode, we most probably need no
|
||||||
// new managers.
|
// new managers.
|
||||||
while (!shouldThrowAwayManagers && myManagers.size() == maxManagers) {
|
while (!shouldThrowAwayManagers && myManagers.size() == maxManagers) {
|
||||||
@ -64,12 +59,10 @@ public class SocketManagerProducer extends Thread {
|
|||||||
// produce a new manager, regardless whether it is needed
|
// produce a new manager, regardless whether it is needed
|
||||||
// or not. Do not synchronized this part, since it can be
|
// or not. Do not synchronized this part, since it can be
|
||||||
// quite time-consuming.
|
// quite time-consuming.
|
||||||
I2PSocketManager newManager =
|
I2PSocketManager newManager = I2PSocketManagerFactory.createManager(host, port, new Properties());
|
||||||
I2PSocketManagerFactory.createManager(host, port,
|
|
||||||
new Properties());
|
|
||||||
// when done, check if it is needed.
|
// when done, check if it is needed.
|
||||||
synchronized(this) {
|
synchronized (this) {
|
||||||
while(myManagers.size() == maxManagers) {
|
while (myManagers.size() == maxManagers) {
|
||||||
myWait();
|
myWait();
|
||||||
}
|
}
|
||||||
myManagers.add(newManager);
|
myManagers.add(newManager);
|
||||||
@ -89,7 +82,7 @@ public class SocketManagerProducer extends Thread {
|
|||||||
I2PSocketManager result = (I2PSocketManager) usedManagers.get(dest);
|
I2PSocketManager result = (I2PSocketManager) usedManagers.get(dest);
|
||||||
if (result == null) {
|
if (result == null) {
|
||||||
result = getManager();
|
result = getManager();
|
||||||
usedManagers.put(dest,result);
|
usedManagers.put(dest, result);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@ -105,7 +98,7 @@ public class SocketManagerProducer extends Thread {
|
|||||||
while (myManagers.size() == 0) {
|
while (myManagers.size() == 0) {
|
||||||
myWait(); // no manager here, so wait until one is produced
|
myWait(); // no manager here, so wait until one is produced
|
||||||
}
|
}
|
||||||
int which = (int)(Math.random()*myManagers.size());
|
int which = (int) (Math.random() * myManagers.size());
|
||||||
I2PSocketManager result = (I2PSocketManager) myManagers.get(which);
|
I2PSocketManager result = (I2PSocketManager) myManagers.get(which);
|
||||||
if (shouldThrowAwayManagers) {
|
if (shouldThrowAwayManagers) {
|
||||||
myManagers.remove(which);
|
myManagers.remove(which);
|
||||||
|
@ -16,12 +16,11 @@ public class ChainFilter implements Filter {
|
|||||||
|
|
||||||
private Collection filters; // perhaps protected?
|
private Collection filters; // perhaps protected?
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param filters A collection (list) of filters to chain to
|
* @param filters A collection (list) of filters to chain to
|
||||||
*/
|
*/
|
||||||
public ChainFilter(Collection filters) {
|
public ChainFilter(Collection filters) {
|
||||||
this.filters=filters;
|
this.filters = filters;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* (non-Javadoc)
|
/* (non-Javadoc)
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
package net.i2p.httptunnel.handler;
|
package net.i2p.httptunnel.handler;
|
||||||
|
|
||||||
import java.io.BufferedInputStream;
|
import java.io.BufferedInputStream;
|
||||||
import java.io.BufferedOutputStream;
|
import java.io.BufferedOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@ -27,8 +28,8 @@ public class EepHandler {
|
|||||||
|
|
||||||
protected ErrorHandler errorHandler;
|
protected ErrorHandler errorHandler;
|
||||||
|
|
||||||
/* package private */ EepHandler(ErrorHandler eh) {
|
/* package private */EepHandler(ErrorHandler eh) {
|
||||||
errorHandler=eh;
|
errorHandler = eh;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -40,13 +41,11 @@ public class EepHandler {
|
|||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
public void handle(Request req, HTTPListener httpl, OutputStream out,
|
public void handle(Request req, HTTPListener httpl, OutputStream out,
|
||||||
/* boolean fromProxy, */ String destination)
|
/* boolean fromProxy, */String destination) throws IOException {
|
||||||
throws IOException {
|
|
||||||
SocketManagerProducer smp = httpl.getSMP();
|
SocketManagerProducer smp = httpl.getSMP();
|
||||||
Destination dest = NamingService.getInstance().lookup(destination);
|
Destination dest = NamingService.getInstance().lookup(destination);
|
||||||
if (dest == null) {
|
if (dest == null) {
|
||||||
errorHandler.handle(req, httpl, out,
|
errorHandler.handle(req, httpl, out, "Could not lookup host: " + destination);
|
||||||
"Could not lookup host: "+destination);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
I2PSocketManager sm = smp.getManager(destination);
|
I2PSocketManager sm = smp.getManager(destination);
|
||||||
@ -66,13 +65,12 @@ public class EepHandler {
|
|||||||
* @return boolean, true if something was written, false otherwise.
|
* @return boolean, true if something was written, false otherwise.
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
public boolean handle(Request req, Filter f, OutputStream out,
|
public boolean handle(Request req, Filter f, OutputStream out, Destination dest, I2PSocketManager sm)
|
||||||
Destination dest, I2PSocketManager sm)
|
|
||||||
throws IOException {
|
throws IOException {
|
||||||
I2PSocket s = null;
|
I2PSocket s = null;
|
||||||
boolean written = false;
|
boolean written = false;
|
||||||
try {
|
try {
|
||||||
synchronized(sm) {
|
synchronized (sm) {
|
||||||
s = sm.connect(dest, new I2PSocketOptions());
|
s = sm.connect(dest, new I2PSocketOptions());
|
||||||
}
|
}
|
||||||
InputStream in = new BufferedInputStream(s.getInputStream());
|
InputStream in = new BufferedInputStream(s.getInputStream());
|
||||||
@ -81,19 +79,19 @@ public class EepHandler {
|
|||||||
sout.flush();
|
sout.flush();
|
||||||
byte[] buffer = new byte[16384], filtered;
|
byte[] buffer = new byte[16384], filtered;
|
||||||
int len;
|
int len;
|
||||||
while ((len=in.read(buffer)) != -1) {
|
while ((len = in.read(buffer)) != -1) {
|
||||||
if (len != buffer.length) {
|
if (len != buffer.length) {
|
||||||
byte[] b2 = new byte[len];
|
byte[] b2 = new byte[len];
|
||||||
System.arraycopy(buffer, 0, b2, 0, len);
|
System.arraycopy(buffer, 0, b2, 0, len);
|
||||||
filtered=f.filter(b2);
|
filtered = f.filter(b2);
|
||||||
} else {
|
} else {
|
||||||
filtered=f.filter(buffer);
|
filtered = f.filter(buffer);
|
||||||
}
|
}
|
||||||
written=true;
|
written = true;
|
||||||
out.write(filtered);
|
out.write(filtered);
|
||||||
}
|
}
|
||||||
filtered=f.finish();
|
filtered = f.finish();
|
||||||
written=true;
|
written = true;
|
||||||
out.write(filtered);
|
out.write(filtered);
|
||||||
out.flush();
|
out.flush();
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
package net.i2p.httptunnel.handler;
|
package net.i2p.httptunnel.handler;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
|
|
||||||
@ -13,7 +14,7 @@ public class ErrorHandler {
|
|||||||
|
|
||||||
private static final Log _log = new Log(ErrorHandler.class);
|
private static final Log _log = new Log(ErrorHandler.class);
|
||||||
|
|
||||||
/* package private */ ErrorHandler() {
|
/* package private */ErrorHandler() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -24,20 +25,17 @@ public class ErrorHandler {
|
|||||||
* @param error the error that happened
|
* @param error the error that happened
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
public void handle(Request req, HTTPListener httpl,
|
public void handle(Request req, HTTPListener httpl, OutputStream out, String error) throws IOException {
|
||||||
OutputStream out, String error) throws IOException {
|
|
||||||
// FIXME: Make nicer messages for more likely errors.
|
// FIXME: Make nicer messages for more likely errors.
|
||||||
out.write(("HTTP/1.1 500 Internal Server Error\r\n"+
|
out
|
||||||
"Content-Type: text/html; charset=iso-8859-1\r\n\r\n")
|
.write(("HTTP/1.1 500 Internal Server Error\r\n" + "Content-Type: text/html; charset=iso-8859-1\r\n\r\n")
|
||||||
.getBytes("ISO-8859-1"));
|
.getBytes("ISO-8859-1"));
|
||||||
out.write(("<html><head><title>"+error+"</title></head><body><h1>"+
|
out
|
||||||
error+"</h1>An internal error occurred while "+
|
.write(("<html><head><title>" + error + "</title></head><body><h1>" + error
|
||||||
"handling a request by HTTPTunnel:<br><b>"+error+
|
+ "</h1>An internal error occurred while " + "handling a request by HTTPTunnel:<br><b>" + error + "</b><h2>Complete request:</h2><b>---</b><br><i><pre>\r\n")
|
||||||
"</b><h2>Complete request:</h2><b>---</b><br><i><pre>\r\n")
|
|
||||||
.getBytes("ISO-8859-1"));
|
.getBytes("ISO-8859-1"));
|
||||||
out.write(req.toByteArray());
|
out.write(req.toByteArray());
|
||||||
out.write(("</pre></i><br><b>---</b></body></html>")
|
out.write(("</pre></i><br><b>---</b></body></html>").getBytes("ISO-8859-1"));
|
||||||
.getBytes("ISO-8859-1"));
|
|
||||||
out.flush();
|
out.flush();
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,4 +1,5 @@
|
|||||||
package net.i2p.httptunnel.handler;
|
package net.i2p.httptunnel.handler;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
|
|
||||||
@ -14,7 +15,7 @@ public class LocalHandler {
|
|||||||
|
|
||||||
private static final Log _log = new Log(LocalHandler.class);
|
private static final Log _log = new Log(LocalHandler.class);
|
||||||
|
|
||||||
/* package private */ LocalHandler() {
|
/* package private */LocalHandler() {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -27,12 +28,12 @@ public class LocalHandler {
|
|||||||
/*, boolean fromProxy */) throws IOException {
|
/*, boolean fromProxy */) throws IOException {
|
||||||
//FIXME: separate multiple pages, not only a start page
|
//FIXME: separate multiple pages, not only a start page
|
||||||
//FIXME: provide some info on this page
|
//FIXME: provide some info on this page
|
||||||
out.write(("HTTP/1.1 200 Document following\r\n"+
|
out
|
||||||
"Content-Type: text/html; charset=iso-8859-1\r\n\r\n"+
|
.write(("HTTP/1.1 200 Document following\r\n" + "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
|
||||||
"<html><head><title>Welcome to I2P HTTPTunnel</title>"+
|
+ "<html><head><title>Welcome to I2P HTTPTunnel</title>"
|
||||||
"</head><body><h1>Welcome to I2P HTTPTunnel</h1>You can "+
|
+ "</head><body><h1>Welcome to I2P HTTPTunnel</h1>You can "
|
||||||
"browse Eepsites by adding an eepsite name to the request."+
|
+ "browse Eepsites by adding an eepsite name to the request." + "</body></html>")
|
||||||
"</body></html>").getBytes("ISO-8859-1"));
|
.getBytes("ISO-8859-1"));
|
||||||
out.flush();
|
out.flush();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -43,8 +44,7 @@ public class LocalHandler {
|
|||||||
* @param out where to write the results
|
* @param out where to write the results
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
public void handleProxyConfWarning(Request req, HTTPListener httpl,
|
public void handleProxyConfWarning(Request req, HTTPListener httpl, OutputStream out) throws IOException {
|
||||||
OutputStream out) throws IOException {
|
|
||||||
//FIXME
|
//FIXME
|
||||||
throw new IOException("jrandom ate the deprecated method. mooo");
|
throw new IOException("jrandom ate the deprecated method. mooo");
|
||||||
//httpl.handleNotImplemented(out);
|
//httpl.handleNotImplemented(out);
|
||||||
@ -58,8 +58,7 @@ public class LocalHandler {
|
|||||||
* @param out where to write the results
|
* @param out where to write the results
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
public void handleHTTPWarning(Request req, HTTPListener httpl,
|
public void handleHTTPWarning(Request req, HTTPListener httpl, OutputStream out /*, boolean fromProxy */)
|
||||||
OutputStream out /*, boolean fromProxy */)
|
|
||||||
throws IOException {
|
throws IOException {
|
||||||
// FIXME
|
// FIXME
|
||||||
throw new IOException("jrandom ate the deprecated method. mooo");
|
throw new IOException("jrandom ate the deprecated method. mooo");
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
package net.i2p.httptunnel.handler;
|
package net.i2p.httptunnel.handler;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
|
|
||||||
@ -19,7 +20,7 @@ public class ProxyHandler extends EepHandler {
|
|||||||
|
|
||||||
private static final Log _log = new Log(ErrorHandler.class);
|
private static final Log _log = new Log(ErrorHandler.class);
|
||||||
|
|
||||||
/* package private */ ProxyHandler(ErrorHandler eh) {
|
/* package private */ProxyHandler(ErrorHandler eh) {
|
||||||
super(eh);
|
super(eh);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -34,8 +35,7 @@ public class ProxyHandler extends EepHandler {
|
|||||||
SocketManagerProducer smp = httpl.getSMP();
|
SocketManagerProducer smp = httpl.getSMP();
|
||||||
Destination dest = findProxy();
|
Destination dest = findProxy();
|
||||||
if (dest == null) {
|
if (dest == null) {
|
||||||
errorHandler.handle(req, httpl, out,
|
errorHandler.handle(req, httpl, out, "Could not find proxy");
|
||||||
"Could not find proxy");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// one manager for all proxy requests
|
// one manager for all proxy requests
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
package net.i2p.httptunnel.handler;
|
package net.i2p.httptunnel.handler;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
|
|
||||||
@ -14,10 +15,10 @@ public class RootHandler {
|
|||||||
private static final Log _log = new Log(RootHandler.class);
|
private static final Log _log = new Log(RootHandler.class);
|
||||||
|
|
||||||
private RootHandler() {
|
private RootHandler() {
|
||||||
errorHandler=new ErrorHandler();
|
errorHandler = new ErrorHandler();
|
||||||
localHandler=new LocalHandler();
|
localHandler = new LocalHandler();
|
||||||
proxyHandler=new ProxyHandler(errorHandler);
|
proxyHandler = new ProxyHandler(errorHandler);
|
||||||
eepHandler=new EepHandler(errorHandler);
|
eepHandler = new EepHandler(errorHandler);
|
||||||
}
|
}
|
||||||
|
|
||||||
private ErrorHandler errorHandler;
|
private ErrorHandler errorHandler;
|
||||||
@ -45,16 +46,15 @@ public class RootHandler {
|
|||||||
* @param out where to write the results
|
* @param out where to write the results
|
||||||
* @throws IOException
|
* @throws IOException
|
||||||
*/
|
*/
|
||||||
public void handle(Request req, HTTPListener httpl,
|
public void handle(Request req, HTTPListener httpl, OutputStream out) throws IOException {
|
||||||
OutputStream out) throws IOException {
|
String url = req.getURL();
|
||||||
String url=req.getURL();
|
|
||||||
System.out.println(url);
|
System.out.println(url);
|
||||||
/* boolean byProxy = false; */
|
/* boolean byProxy = false; */
|
||||||
int pos;
|
int pos;
|
||||||
if (url.startsWith("http://")) { // access via proxy
|
if (url.startsWith("http://")) { // access via proxy
|
||||||
/* byProxy=true; */
|
/* byProxy=true; */
|
||||||
if (httpl.firstProxyUse()) {
|
if (httpl.firstProxyUse()) {
|
||||||
localHandler.handleProxyConfWarning(req,httpl,out);
|
localHandler.handleProxyConfWarning(req, httpl, out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
url = url.substring(7);
|
url = url.substring(7);
|
||||||
@ -65,15 +65,15 @@ public class RootHandler {
|
|||||||
errorHandler.handle(req, httpl, out, "No host end in URL");
|
errorHandler.handle(req, httpl, out, "No host end in URL");
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
host = url.substring(0,pos);
|
host = url.substring(0, pos);
|
||||||
url = url.substring(pos);
|
url = url.substring(pos);
|
||||||
if ("i2p".equals(host) || "i2p.i2p".equals(host)) {
|
if ("i2p".equals(host) || "i2p.i2p".equals(host)) {
|
||||||
// normal request; go on below...
|
// normal request; go on below...
|
||||||
} else if (host.endsWith(".i2p")) {
|
} else if (host.endsWith(".i2p")) {
|
||||||
// "old" service request, send a redirect...
|
// "old" service request, send a redirect...
|
||||||
out.write(("HTTP/1.1 302 Moved\r\nLocation: "+
|
out
|
||||||
"http://i2p.i2p/"+host+url+
|
.write(("HTTP/1.1 302 Moved\r\nLocation: " + "http://i2p.i2p/" + host + url + "\r\n\r\n")
|
||||||
"\r\n\r\n").getBytes("ISO-8859-1"));
|
.getBytes("ISO-8859-1"));
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
// this is for proxying to the real web
|
// this is for proxying to the real web
|
||||||
@ -83,21 +83,20 @@ public class RootHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (url.equals("/")) { // main page
|
if (url.equals("/")) { // main page
|
||||||
url="/_/local/index";
|
url = "/_/local/index";
|
||||||
} else if (!url.startsWith("/")) {
|
} else if (!url.startsWith("/")) {
|
||||||
errorHandler.handle(req, httpl, out,
|
errorHandler.handle(req, httpl, out, "No leading slash in URL: " + url);
|
||||||
"No leading slash in URL: "+url);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String dest;
|
String dest;
|
||||||
url=url.substring(1);
|
url = url.substring(1);
|
||||||
pos = url.indexOf("/");
|
pos = url.indexOf("/");
|
||||||
if (pos == -1) {
|
if (pos == -1) {
|
||||||
dest=url;
|
dest = url;
|
||||||
url="/";
|
url = "/";
|
||||||
} else {
|
} else {
|
||||||
dest = url.substring(0,pos);
|
dest = url.substring(0, pos);
|
||||||
url=url.substring(pos);
|
url = url.substring(pos);
|
||||||
}
|
}
|
||||||
req.setURL(url);
|
req.setURL(url);
|
||||||
if (dest.equals("_")) { // no eepsite
|
if (dest.equals("_")) { // no eepsite
|
||||||
@ -107,14 +106,13 @@ public class RootHandler {
|
|||||||
} else if (url.startsWith("/http/")) { // http warning
|
} else if (url.startsWith("/http/")) { // http warning
|
||||||
localHandler.handleHTTPWarning(req, httpl, out /*, byProxy */);
|
localHandler.handleHTTPWarning(req, httpl, out /*, byProxy */);
|
||||||
} else if (url.startsWith("/proxy/")) { // http proxying
|
} else if (url.startsWith("/proxy/")) { // http proxying
|
||||||
req.setURL("http://"+url.substring(7));
|
req.setURL("http://" + url.substring(7));
|
||||||
proxyHandler.handle(req, httpl, out /*, byProxy */);
|
proxyHandler.handle(req, httpl, out /*, byProxy */);
|
||||||
} else {
|
} else {
|
||||||
errorHandler.handle(req, httpl, out,
|
errorHandler.handle(req, httpl, out, "No local handler for this URL: " + url);
|
||||||
"No local handler for this URL: "+url);
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
eepHandler.handle(req, httpl, out, /* byProxy, */ dest);
|
eepHandler.handle(req, httpl, out, /* byProxy, */dest);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -23,9 +23,12 @@ class BufferLogger implements Logging {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private final static String EMPTY = "";
|
private final static String EMPTY = "";
|
||||||
|
|
||||||
public String getBuffer() {
|
public String getBuffer() {
|
||||||
if (_ignore) return EMPTY;
|
if (_ignore)
|
||||||
else return new String(_baos.toByteArray());
|
return EMPTY;
|
||||||
|
else
|
||||||
|
return new String(_baos.toByteArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -62,24 +62,21 @@ import net.i2p.util.EventDispatcher;
|
|||||||
import net.i2p.util.EventDispatcherImpl;
|
import net.i2p.util.EventDispatcherImpl;
|
||||||
import net.i2p.util.Log;
|
import net.i2p.util.Log;
|
||||||
|
|
||||||
|
|
||||||
public class I2PTunnel implements Logging, EventDispatcher {
|
public class I2PTunnel implements Logging, EventDispatcher {
|
||||||
private final static Log _log = new Log(I2PTunnel.class);
|
private final static Log _log = new Log(I2PTunnel.class);
|
||||||
private final EventDispatcherImpl _event = new EventDispatcherImpl();
|
private final EventDispatcherImpl _event = new EventDispatcherImpl();
|
||||||
|
|
||||||
public static final int PACKET_DELAY=100;
|
public static final int PACKET_DELAY = 100;
|
||||||
|
|
||||||
public static boolean ownDest = false;
|
public static boolean ownDest = false;
|
||||||
|
|
||||||
public static String port =
|
public static String port = System.getProperty(I2PClient.PROP_TCP_PORT, "7654");
|
||||||
System.getProperty(I2PClient.PROP_TCP_PORT, "7654");
|
public static String host = System.getProperty(I2PClient.PROP_TCP_HOST, "127.0.0.1");
|
||||||
public static String host = System.getProperty
|
|
||||||
(I2PClient.PROP_TCP_HOST,"127.0.0.1");
|
|
||||||
public static String listenHost = host;
|
public static String listenHost = host;
|
||||||
|
|
||||||
private static final String nocli_args[] = {"-nocli", "-die"};
|
private static final String nocli_args[] = { "-nocli", "-die"};
|
||||||
|
|
||||||
private List tasks=new ArrayList();
|
private List tasks = new ArrayList();
|
||||||
private int next_task_id = 1;
|
private int next_task_id = 1;
|
||||||
|
|
||||||
private Set listeners = new HashSet();
|
private Set listeners = new HashSet();
|
||||||
@ -95,41 +92,42 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
public I2PTunnel(String[] args) {
|
public I2PTunnel(String[] args) {
|
||||||
this(args, null);
|
this(args, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public I2PTunnel(String[] args, ConnectionEventListener lsnr) {
|
public I2PTunnel(String[] args, ConnectionEventListener lsnr) {
|
||||||
addConnectionEventListener(lsnr);
|
addConnectionEventListener(lsnr);
|
||||||
boolean gui=true;
|
boolean gui = true;
|
||||||
boolean checkRunByE = true;;
|
boolean checkRunByE = true;
|
||||||
boolean cli=true;
|
boolean cli = true;
|
||||||
boolean dontDie = true;
|
boolean dontDie = true;
|
||||||
for(int i=0;i<args.length;i++) {
|
for (int i = 0; i < args.length; i++) {
|
||||||
if (args[i].equals("-die")) {
|
if (args[i].equals("-die")) {
|
||||||
dontDie = false;
|
dontDie = false;
|
||||||
gui=false;
|
gui = false;
|
||||||
cli=false;
|
cli = false;
|
||||||
checkRunByE=false;
|
checkRunByE = false;
|
||||||
} else if (args[i].equals("-nogui")) {
|
} else if (args[i].equals("-nogui")) {
|
||||||
gui=false;
|
gui = false;
|
||||||
_log.warn("The `-nogui' option of I2PTunnel is deprecated.\n"+
|
_log.warn("The `-nogui' option of I2PTunnel is deprecated.\n"
|
||||||
"Use `-cli', `-nocli' (aka `-wait') or `-die' instead.");
|
+ "Use `-cli', `-nocli' (aka `-wait') or `-die' instead.");
|
||||||
} else if (args[i].equals("-cli")) {
|
} else if (args[i].equals("-cli")) {
|
||||||
gui=false;
|
gui = false;
|
||||||
cli=true;
|
cli = true;
|
||||||
checkRunByE=false;
|
checkRunByE = false;
|
||||||
} else if (args[i].equals("-nocli") || args[i].equals("-wait")) {
|
} else if (args[i].equals("-nocli") || args[i].equals("-wait")) {
|
||||||
gui=false;
|
gui = false;
|
||||||
cli=false;
|
cli = false;
|
||||||
checkRunByE=false;
|
checkRunByE = false;
|
||||||
} else if (args[i].equals("-e")) {
|
} else if (args[i].equals("-e")) {
|
||||||
runCommand(args[i+1], this);
|
runCommand(args[i + 1], this);
|
||||||
i++;
|
i++;
|
||||||
if (checkRunByE) {
|
if (checkRunByE) {
|
||||||
checkRunByE = false;
|
checkRunByE = false;
|
||||||
cli=false;
|
cli = false;
|
||||||
}
|
}
|
||||||
} else if (new File(args[i]).exists()) {
|
} else if (new File(args[i]).exists()) {
|
||||||
runCommand("run "+args[i], this);
|
runCommand("run " + args[i], this);
|
||||||
} else {
|
} else {
|
||||||
System.out.println("Unknown parameter "+args[i]);
|
System.out.println("Unknown parameter " + args[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (gui) {
|
if (gui) {
|
||||||
@ -137,9 +135,8 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
} else if (cli) {
|
} else if (cli) {
|
||||||
try {
|
try {
|
||||||
System.out.println("Enter 'help' for help.");
|
System.out.println("Enter 'help' for help.");
|
||||||
BufferedReader r = new BufferedReader
|
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
|
||||||
(new InputStreamReader(System.in));
|
while (true) {
|
||||||
while(true) {
|
|
||||||
System.out.print("I2PTunnel>");
|
System.out.print("I2PTunnel>");
|
||||||
String cmd = r.readLine();
|
String cmd = r.readLine();
|
||||||
if (cmd == null) break;
|
if (cmd == null) break;
|
||||||
@ -152,13 +149,15 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
|
|
||||||
while (dontDie) {
|
while (dontDie) {
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
try { wait(); } catch (InterruptedException ie) {}
|
try {
|
||||||
|
wait();
|
||||||
|
} catch (InterruptedException ie) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addtask (I2PTunnelTask tsk)
|
private void addtask(I2PTunnelTask tsk) {
|
||||||
{
|
|
||||||
tsk.setTunnel(this);
|
tsk.setTunnel(this);
|
||||||
if (tsk.isOpen()) {
|
if (tsk.isOpen()) {
|
||||||
tsk.setId(next_task_id);
|
tsk.setId(next_task_id);
|
||||||
@ -178,11 +177,12 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
vals[i] = tok.nextToken();
|
vals[i] = tok.nextToken();
|
||||||
return vals;
|
return vals;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void runCommand(String cmd, Logging l) {
|
public void runCommand(String cmd, Logging l) {
|
||||||
if (cmd.indexOf(" ")== -1) cmd+=" ";
|
if (cmd.indexOf(" ") == -1) cmd += " ";
|
||||||
int iii=cmd.indexOf(" ");
|
int iii = cmd.indexOf(" ");
|
||||||
String cmdname= cmd.substring(0,iii).toLowerCase();
|
String cmdname = cmd.substring(0, iii).toLowerCase();
|
||||||
String allargs = cmd.substring(iii+1);
|
String allargs = cmd.substring(iii + 1);
|
||||||
String[] args = split(allargs, " "); // .split(" "); // java 1.4
|
String[] args = split(allargs, " "); // .split(" "); // java 1.4
|
||||||
|
|
||||||
if ("help".equals(cmdname)) {
|
if ("help".equals(cmdname)) {
|
||||||
@ -262,7 +262,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param l logger to receive events and output
|
* @param l logger to receive events and output
|
||||||
*/
|
*/
|
||||||
public void runServer(String args[], Logging l) {
|
public void runServer(String args[], Logging l) {
|
||||||
if (args.length==3) {
|
if (args.length == 3) {
|
||||||
InetAddress serverHost = null;
|
InetAddress serverHost = null;
|
||||||
int portNum = -1;
|
int portNum = -1;
|
||||||
File privKeyFile = null;
|
File privKeyFile = null;
|
||||||
@ -292,15 +292,13 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
I2PTunnelTask task;
|
I2PTunnelTask task;
|
||||||
task = new I2PTunnelServer(serverHost, portNum, privKeyFile,
|
task = new I2PTunnelServer(serverHost, portNum, privKeyFile, args[2], l, (EventDispatcher) this);
|
||||||
args[2], l, (EventDispatcher)this);
|
|
||||||
addtask(task);
|
addtask(task);
|
||||||
notifyEvent("serverTaskId", new Integer(task.getId()));
|
notifyEvent("serverTaskId", new Integer(task.getId()));
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
l.log("server <host> <port> <privkeyfile>");
|
l.log("server <host> <port> <privkeyfile>");
|
||||||
l.log(" creates a server that sends all incoming data\n"+
|
l.log(" creates a server that sends all incoming data\n" + " of its destination to host:port.");
|
||||||
" of its destination to host:port.");
|
|
||||||
notifyEvent("serverTaskId", new Integer(-1));
|
notifyEvent("serverTaskId", new Integer(-1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -317,7 +315,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param l logger to receive events and output
|
* @param l logger to receive events and output
|
||||||
*/
|
*/
|
||||||
public void runTextServer(String args[], Logging l) {
|
public void runTextServer(String args[], Logging l) {
|
||||||
if (args.length==3) {
|
if (args.length == 3) {
|
||||||
InetAddress serverHost = null;
|
InetAddress serverHost = null;
|
||||||
int portNum = -1;
|
int portNum = -1;
|
||||||
try {
|
try {
|
||||||
@ -339,14 +337,12 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
I2PTunnelTask task;
|
I2PTunnelTask task;
|
||||||
task = new I2PTunnelServer(serverHost, portNum, args[2], l,
|
task = new I2PTunnelServer(serverHost, portNum, args[2], l, (EventDispatcher) this);
|
||||||
(EventDispatcher)this);
|
|
||||||
addtask(task);
|
addtask(task);
|
||||||
notifyEvent("serverTaskId", new Integer(task.getId()));
|
notifyEvent("serverTaskId", new Integer(task.getId()));
|
||||||
} else {
|
} else {
|
||||||
l.log("textserver <host> <port> <privkey>");
|
l.log("textserver <host> <port> <privkey>");
|
||||||
l.log(" creates a server that sends all incoming data\n"+
|
l.log(" creates a server that sends all incoming data\n" + " of its destination to host:port.");
|
||||||
" of its destination to host:port.");
|
|
||||||
notifyEvent("textserverTaskId", new Integer(-1));
|
notifyEvent("textserverTaskId", new Integer(-1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -364,7 +360,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param l logger to receive events and output
|
* @param l logger to receive events and output
|
||||||
*/
|
*/
|
||||||
public void runClient(String args[], Logging l) {
|
public void runClient(String args[], Logging l) {
|
||||||
if (args.length==2) {
|
if (args.length == 2) {
|
||||||
int port = -1;
|
int port = -1;
|
||||||
try {
|
try {
|
||||||
port = Integer.parseInt(args[0]);
|
port = Integer.parseInt(args[0]);
|
||||||
@ -375,14 +371,13 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
I2PTunnelTask task;
|
I2PTunnelTask task;
|
||||||
task = new I2PTunnelClient(port, args[1], l, ownDest,
|
task = new I2PTunnelClient(port, args[1], l, ownDest, (EventDispatcher) this);
|
||||||
(EventDispatcher)this);
|
|
||||||
addtask(task);
|
addtask(task);
|
||||||
notifyEvent("clientTaskId", new Integer(task.getId()));
|
notifyEvent("clientTaskId", new Integer(task.getId()));
|
||||||
} else {
|
} else {
|
||||||
l.log("client <port> <pubkey>|file:<pubkeyfile>");
|
l.log("client <port> <pubkey>|file:<pubkeyfile>");
|
||||||
l.log(" creates a client that forwards port to the pubkey.\n"+
|
l.log(" creates a client that forwards port to the pubkey.\n"
|
||||||
" use 0 as port to get a free port assigned.");
|
+ " use 0 as port to get a free port assigned.");
|
||||||
notifyEvent("clientTaskId", new Integer(-1));
|
notifyEvent("clientTaskId", new Integer(-1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -413,8 +408,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
proxy = args[1];
|
proxy = args[1];
|
||||||
}
|
}
|
||||||
I2PTunnelTask task;
|
I2PTunnelTask task;
|
||||||
task = new I2PTunnelHTTPClient(port, l, ownDest, proxy,
|
task = new I2PTunnelHTTPClient(port, l, ownDest, proxy, (EventDispatcher) this);
|
||||||
(EventDispatcher)this);
|
|
||||||
addtask(task);
|
addtask(task);
|
||||||
notifyEvent("httpclientTaskId", new Integer(task.getId()));
|
notifyEvent("httpclientTaskId", new Integer(task.getId()));
|
||||||
} else {
|
} else {
|
||||||
@ -451,7 +445,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
I2PTunnelTask task;
|
I2PTunnelTask task;
|
||||||
task = new I2PSOCKSTunnel(port, l, ownDest, (EventDispatcher)this);
|
task = new I2PSOCKSTunnel(port, l, ownDest, (EventDispatcher) this);
|
||||||
addtask(task);
|
addtask(task);
|
||||||
notifyEvent("sockstunnelTaskId", new Integer(task.getId()));
|
notifyEvent("sockstunnelTaskId", new Integer(task.getId()));
|
||||||
} else {
|
} else {
|
||||||
@ -470,10 +464,10 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param l logger to receive events and output
|
* @param l logger to receive events and output
|
||||||
*/
|
*/
|
||||||
public void runConfig(String args[], Logging l) {
|
public void runConfig(String args[], Logging l) {
|
||||||
if (args.length==2) {
|
if (args.length == 2) {
|
||||||
host=args[0];
|
host = args[0];
|
||||||
listenHost=host;
|
listenHost = host;
|
||||||
port=args[1];
|
port = args[1];
|
||||||
notifyEvent("configResult", "ok");
|
notifyEvent("configResult", "ok");
|
||||||
} else {
|
} else {
|
||||||
l.log("config <i2phost> <i2pport>");
|
l.log("config <i2phost> <i2pport>");
|
||||||
@ -491,15 +485,12 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param l logger to receive events and output
|
* @param l logger to receive events and output
|
||||||
*/
|
*/
|
||||||
public void runOwnDest(String args[], Logging l) {
|
public void runOwnDest(String args[], Logging l) {
|
||||||
if (args.length==1 &&
|
if (args.length == 1 && (args[0].equalsIgnoreCase("yes") || args[0].equalsIgnoreCase("no"))) {
|
||||||
(args[0].equalsIgnoreCase("yes")
|
|
||||||
|| args[0].equalsIgnoreCase("no"))) {
|
|
||||||
ownDest = args[0].equalsIgnoreCase("yes");
|
ownDest = args[0].equalsIgnoreCase("yes");
|
||||||
notifyEvent("owndestResult", "ok");
|
notifyEvent("owndestResult", "ok");
|
||||||
} else {
|
} else {
|
||||||
l.log("owndest yes|no");
|
l.log("owndest yes|no");
|
||||||
l.log(" Specifies whether to use its own destination \n"+
|
l.log(" Specifies whether to use its own destination \n" + " for each outgoing tunnel");
|
||||||
" for each outgoing tunnel");
|
|
||||||
notifyEvent("owndestResult", "error");
|
notifyEvent("owndestResult", "error");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -513,8 +504,8 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param l logger to receive events and output
|
* @param l logger to receive events and output
|
||||||
*/
|
*/
|
||||||
public void runListenOn(String args[], Logging l) {
|
public void runListenOn(String args[], Logging l) {
|
||||||
if (args.length==1) {
|
if (args.length == 1) {
|
||||||
listenHost=args[0];
|
listenHost = args[0];
|
||||||
notifyEvent("listen_onResult", "ok");
|
notifyEvent("listen_onResult", "ok");
|
||||||
} else {
|
} else {
|
||||||
l.log("listen_on <ip>");
|
l.log("listen_on <ip>");
|
||||||
@ -532,10 +523,10 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param l logger to receive events and output
|
* @param l logger to receive events and output
|
||||||
*/
|
*/
|
||||||
public void runGenKeys(String args[], Logging l) {
|
public void runGenKeys(String args[], Logging l) {
|
||||||
OutputStream pubdest=null;
|
OutputStream pubdest = null;
|
||||||
if (args.length == 2) {
|
if (args.length == 2) {
|
||||||
try {
|
try {
|
||||||
pubdest=new FileOutputStream(args[1]);
|
pubdest = new FileOutputStream(args[1]);
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
l.log("Error opening output stream");
|
l.log("Error opening output stream");
|
||||||
_log.error("Error generating keys to out", ioe);
|
_log.error("Error generating keys to out", ioe);
|
||||||
@ -544,11 +535,9 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
}
|
}
|
||||||
} else if (args.length != 1) {
|
} else if (args.length != 1) {
|
||||||
l.log("genkeys <privkeyfile> [<pubkeyfile>]");
|
l.log("genkeys <privkeyfile> [<pubkeyfile>]");
|
||||||
l.log(" creates a new keypair and prints the public key.\n"+
|
l.log(" creates a new keypair and prints the public key.\n"
|
||||||
" if pubkeyfile is given, saves the public key there."+
|
+ " if pubkeyfile is given, saves the public key there." + "\n"
|
||||||
"\n"+
|
+ " if the privkeyfile already exists, just print/save" + "the pubkey.");
|
||||||
" if the privkeyfile already exists, just print/save"+
|
|
||||||
"the pubkey.");
|
|
||||||
notifyEvent("genkeysResult", "error");
|
notifyEvent("genkeysResult", "error");
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@ -579,7 +568,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
ByteArrayOutputStream privkey = new ByteArrayOutputStream(512);
|
ByteArrayOutputStream privkey = new ByteArrayOutputStream(512);
|
||||||
ByteArrayOutputStream pubkey = new ByteArrayOutputStream(512);
|
ByteArrayOutputStream pubkey = new ByteArrayOutputStream(512);
|
||||||
makeKey(privkey, pubkey, l);
|
makeKey(privkey, pubkey, l);
|
||||||
l.log("Private key: "+Base64.encode(privkey.toByteArray()));
|
l.log("Private key: " + Base64.encode(privkey.toByteArray()));
|
||||||
notifyEvent("privateKey", Base64.encode(privkey.toByteArray()));
|
notifyEvent("privateKey", Base64.encode(privkey.toByteArray()));
|
||||||
notifyEvent("publicDestination", Base64.encode(pubkey.toByteArray()));
|
notifyEvent("publicDestination", Base64.encode(pubkey.toByteArray()));
|
||||||
}
|
}
|
||||||
@ -615,7 +604,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
public void runList(Logging l) {
|
public void runList(Logging l) {
|
||||||
purgetasks(l);
|
purgetasks(l);
|
||||||
synchronized (tasks) {
|
synchronized (tasks) {
|
||||||
for (int i=0;i<tasks.size();i++) {
|
for (int i = 0; i < tasks.size(); i++) {
|
||||||
I2PTunnelTask t = (I2PTunnelTask) tasks.get(i);
|
I2PTunnelTask t = (I2PTunnelTask) tasks.get(i);
|
||||||
l.log("[" + t.getId() + "] " + t.toString());
|
l.log("[" + t.getId() + "] " + t.toString());
|
||||||
}
|
}
|
||||||
@ -635,15 +624,15 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
public void runClose(String args[], Logging l) {
|
public void runClose(String args[], Logging l) {
|
||||||
if (args.length == 0 || args.length > 2) {
|
if (args.length == 0 || args.length > 2) {
|
||||||
l.log("close [forced] <jobnumber>|all");
|
l.log("close [forced] <jobnumber>|all");
|
||||||
l.log(" stop running tasks. either only one or all.\n"+
|
l.log(" stop running tasks. either only one or all.\n"
|
||||||
" use 'forced' to also stop tasks with active connections.\n"+
|
+ " use 'forced' to also stop tasks with active connections.\n"
|
||||||
" use the 'list' command to show the job numbers");
|
+ " use the 'list' command to show the job numbers");
|
||||||
notifyEvent("closeResult", "error");
|
notifyEvent("closeResult", "error");
|
||||||
} else {
|
} else {
|
||||||
int argindex=0; // parse optional 'forced' keyword
|
int argindex = 0; // parse optional 'forced' keyword
|
||||||
boolean forced=false;
|
boolean forced = false;
|
||||||
if (args[argindex].equalsIgnoreCase("forced")) {
|
if (args[argindex].equalsIgnoreCase("forced")) {
|
||||||
forced=true;
|
forced = true;
|
||||||
argindex++;
|
argindex++;
|
||||||
}
|
}
|
||||||
if (args[argindex].equalsIgnoreCase("all")) {
|
if (args[argindex].equalsIgnoreCase("all")) {
|
||||||
@ -653,8 +642,8 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
boolean error = false;
|
boolean error = false;
|
||||||
for (int i=0;i<curTasks.size();i++) {
|
for (int i = 0; i < curTasks.size(); i++) {
|
||||||
I2PTunnelTask t = (I2PTunnelTask)curTasks.get(i);
|
I2PTunnelTask t = (I2PTunnelTask) curTasks.get(i);
|
||||||
if (!closetask(t, forced, l)) {
|
if (!closetask(t, forced, l)) {
|
||||||
notifyEvent("closeResult", "error");
|
notifyEvent("closeResult", "error");
|
||||||
error = true;
|
error = true;
|
||||||
@ -664,7 +653,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
if (!closetask(Integer.parseInt(args[argindex]),forced,l)){
|
if (!closetask(Integer.parseInt(args[argindex]), forced, l)) {
|
||||||
notifyEvent("closeResult", "error");
|
notifyEvent("closeResult", "error");
|
||||||
} else {
|
} else {
|
||||||
notifyEvent("closeResult", "ok");
|
notifyEvent("closeResult", "ok");
|
||||||
@ -686,13 +675,12 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param l logger to receive events and output
|
* @param l logger to receive events and output
|
||||||
*/
|
*/
|
||||||
public void runRun(String args[], Logging l) {
|
public void runRun(String args[], Logging l) {
|
||||||
if(args.length==1) {
|
if (args.length == 1) {
|
||||||
try {
|
try {
|
||||||
BufferedReader br =
|
BufferedReader br = new BufferedReader(new FileReader(args[0]));
|
||||||
new BufferedReader(new FileReader(args[0]));
|
|
||||||
String line;
|
String line;
|
||||||
while((line = br.readLine()) != null) {
|
while ((line = br.readLine()) != null) {
|
||||||
runCommand(line,l);
|
runCommand(line, l);
|
||||||
}
|
}
|
||||||
br.close();
|
br.close();
|
||||||
notifyEvent("runResult", "ok");
|
notifyEvent("runResult", "ok");
|
||||||
@ -703,8 +691,8 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
l.log("run <commandfile>");
|
l.log("run <commandfile>");
|
||||||
l.log(" loads commandfile and runs each line in it. \n"+
|
l.log(" loads commandfile and runs each line in it. \n"
|
||||||
" You can also give the filename on the commandline.");
|
+ " You can also give the filename on the commandline.");
|
||||||
notifyEvent("runResult", "error");
|
notifyEvent("runResult", "error");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -749,18 +737,17 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param l logger to receive events and output
|
* @param l logger to receive events and output
|
||||||
*/
|
*/
|
||||||
public void runPing(String allargs, Logging l) {
|
public void runPing(String allargs, Logging l) {
|
||||||
if(allargs.length() != 0) {
|
if (allargs.length() != 0) {
|
||||||
I2PTunnelTask task;
|
I2PTunnelTask task;
|
||||||
// pings always use the main destination
|
// pings always use the main destination
|
||||||
task = new I2Ping(allargs, l, false, (EventDispatcher)this);
|
task = new I2Ping(allargs, l, false, (EventDispatcher) this);
|
||||||
addtask(task);
|
addtask(task);
|
||||||
notifyEvent("pingTaskId", new Integer(task.getId()));
|
notifyEvent("pingTaskId", new Integer(task.getId()));
|
||||||
} else {
|
} else {
|
||||||
l.log("ping <opts> <dest>");
|
l.log("ping <opts> <dest>");
|
||||||
l.log("ping <opts> -h");
|
l.log("ping <opts> -h");
|
||||||
l.log("ping <opts> -l <destlistfile>");
|
l.log("ping <opts> -l <destlistfile>");
|
||||||
l.log(" Tests communication with peers.\n"+
|
l.log(" Tests communication with peers.\n" + " opts can be -ns (nosync) or not.");
|
||||||
" opts can be -ns (nosync) or not.");
|
|
||||||
notifyEvent("pingTaskId", new Integer(-1));
|
notifyEvent("pingTaskId", new Integer(-1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -775,11 +762,10 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
|
|
||||||
_log.debug("closetask(): looking for task " + num);
|
_log.debug("closetask(): looking for task " + num);
|
||||||
synchronized (tasks) {
|
synchronized (tasks) {
|
||||||
for (Iterator it=tasks.iterator(); it.hasNext();) {
|
for (Iterator it = tasks.iterator(); it.hasNext();) {
|
||||||
I2PTunnelTask t = (I2PTunnelTask) it.next();
|
I2PTunnelTask t = (I2PTunnelTask) it.next();
|
||||||
int id = t.getId();
|
int id = t.getId();
|
||||||
_log.debug("closetask(): parsing task " + id + " (" +
|
_log.debug("closetask(): parsing task " + id + " (" + t.toString() + ")");
|
||||||
t.toString() + ")");
|
|
||||||
if (id == num) {
|
if (id == num) {
|
||||||
closed = closetask(t, forced, l);
|
closed = closetask(t, forced, l);
|
||||||
break;
|
break;
|
||||||
@ -811,12 +797,10 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
*/
|
*/
|
||||||
private void purgetasks(Logging l) {
|
private void purgetasks(Logging l) {
|
||||||
synchronized (tasks) {
|
synchronized (tasks) {
|
||||||
for (Iterator it=tasks.iterator(); it.hasNext();) {
|
for (Iterator it = tasks.iterator(); it.hasNext();) {
|
||||||
I2PTunnelTask t = (I2PTunnelTask) it.next();
|
I2PTunnelTask t = (I2PTunnelTask) it.next();
|
||||||
if (!t.isOpen()) {
|
if (!t.isOpen()) {
|
||||||
_log.debug("Purging inactive tunnel: ["
|
_log.debug("Purging inactive tunnel: [" + t.getId() + "] " + t.toString());
|
||||||
+ t.getId() + "] "
|
|
||||||
+ t.toString());
|
|
||||||
it.remove();
|
it.remove();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -840,16 +824,14 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param pubDest location to store the destination
|
* @param pubDest location to store the destination
|
||||||
* @param l logger to send messages to
|
* @param l logger to send messages to
|
||||||
*/
|
*/
|
||||||
public static void makeKey(OutputStream writeTo, OutputStream pubDest,
|
public static void makeKey(OutputStream writeTo, OutputStream pubDest, Logging l) {
|
||||||
Logging l) {
|
|
||||||
try {
|
try {
|
||||||
l.log("Generating new keys...");
|
l.log("Generating new keys...");
|
||||||
ByteArrayOutputStream priv = new ByteArrayOutputStream(),
|
ByteArrayOutputStream priv = new ByteArrayOutputStream(), pub = new ByteArrayOutputStream();
|
||||||
pub = new ByteArrayOutputStream();
|
|
||||||
I2PClient client = I2PClientFactory.createClient();
|
I2PClient client = I2PClientFactory.createClient();
|
||||||
Destination d = client.createDestination(writeTo);
|
Destination d = client.createDestination(writeTo);
|
||||||
l.log("Secret key saved.");
|
l.log("Secret key saved.");
|
||||||
l.log("Public key: "+d.toBase64());
|
l.log("Public key: " + d.toBase64());
|
||||||
writeTo.flush();
|
writeTo.flush();
|
||||||
writeTo.close();
|
writeTo.close();
|
||||||
writePubKey(d, pubDest, l);
|
writePubKey(d, pubDest, l);
|
||||||
@ -867,13 +849,12 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param pubDest stream to write the destination to
|
* @param pubDest stream to write the destination to
|
||||||
* @param l logger to send messages to
|
* @param l logger to send messages to
|
||||||
*/
|
*/
|
||||||
public static void showKey(InputStream readFrom, OutputStream pubDest,
|
public static void showKey(InputStream readFrom, OutputStream pubDest, Logging l) {
|
||||||
Logging l) {
|
|
||||||
try {
|
try {
|
||||||
I2PClient client = I2PClientFactory.createClient();
|
I2PClient client = I2PClientFactory.createClient();
|
||||||
Destination d = new Destination();
|
Destination d = new Destination();
|
||||||
d.readBytes(readFrom);
|
d.readBytes(readFrom);
|
||||||
l.log("Public key: "+d.toBase64());
|
l.log("Public key: " + d.toBase64());
|
||||||
readFrom.close();
|
readFrom.close();
|
||||||
writePubKey(d, pubDest, l);
|
writePubKey(d, pubDest, l);
|
||||||
} catch (I2PException ex) {
|
} catch (I2PException ex) {
|
||||||
@ -890,9 +871,8 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* @param o stream to write the destination to
|
* @param o stream to write the destination to
|
||||||
* @param l logger to send messages to
|
* @param l logger to send messages to
|
||||||
*/
|
*/
|
||||||
private static void writePubKey(Destination d, OutputStream o, Logging l)
|
private static void writePubKey(Destination d, OutputStream o, Logging l) throws I2PException, IOException {
|
||||||
throws I2PException, IOException {
|
if (o == null) return;
|
||||||
if (o==null) return;
|
|
||||||
d.writeBytes(o);
|
d.writeBytes(o);
|
||||||
l.log("Public key saved.");
|
l.log("Public key saved.");
|
||||||
}
|
}
|
||||||
@ -904,14 +884,12 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
* binary Destination structure or the Base64 encoding of that
|
* binary Destination structure or the Base64 encoding of that
|
||||||
* structure.
|
* structure.
|
||||||
*/
|
*/
|
||||||
public static Destination destFromName(String name)
|
public static Destination destFromName(String name) throws DataFormatException {
|
||||||
throws DataFormatException {
|
|
||||||
|
|
||||||
if ( (name == null) || (name.trim().length() <= 0) )
|
if ((name == null) || (name.trim().length() <= 0)) throw new DataFormatException("Empty destination provided");
|
||||||
throw new DataFormatException("Empty destination provided");
|
|
||||||
|
|
||||||
if (name.startsWith("file:")) {
|
if (name.startsWith("file:")) {
|
||||||
Destination result=new Destination();
|
Destination result = new Destination();
|
||||||
byte content[] = null;
|
byte content[] = null;
|
||||||
FileInputStream in = null;
|
FileInputStream in = null;
|
||||||
try {
|
try {
|
||||||
@ -924,21 +902,22 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
System.out.println(ioe.getMessage());
|
System.out.println(ioe.getMessage());
|
||||||
return null;
|
return null;
|
||||||
} finally {
|
} finally {
|
||||||
if (in != null) try { in.close(); } catch (IOException io) {}
|
if (in != null) try {
|
||||||
|
in.close();
|
||||||
|
} catch (IOException io) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
result.fromByteArray(content);
|
result.fromByteArray(content);
|
||||||
return result;
|
return result;
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
if (_log.shouldLog(Log.INFO))
|
if (_log.shouldLog(Log.INFO)) _log.info("File is not a binary destination - trying base64");
|
||||||
_log.info("File is not a binary destination - trying base64");
|
|
||||||
try {
|
try {
|
||||||
byte decoded[] = Base64.decode(new String(content));
|
byte decoded[] = Base64.decode(new String(content));
|
||||||
result.fromByteArray(decoded);
|
result.fromByteArray(decoded);
|
||||||
return result;
|
return result;
|
||||||
} catch (DataFormatException dfe) {
|
} catch (DataFormatException dfe) {
|
||||||
if (_log.shouldLog(Log.WARN))
|
if (_log.shouldLog(Log.WARN)) _log.warn("File is not a base64 destination either - failing!");
|
||||||
_log.warn("File is not a base64 destination either - failing!");
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -955,6 +934,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
listeners.add(lsnr);
|
listeners.add(lsnr);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void removeConnectionEventListener(ConnectionEventListener lsnr) {
|
public void removeConnectionEventListener(ConnectionEventListener lsnr) {
|
||||||
if (lsnr == null) return;
|
if (lsnr == null) return;
|
||||||
synchronized (listeners) {
|
synchronized (listeners) {
|
||||||
@ -971,9 +951,8 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
_log.error("Router disconnected - firing notification events");
|
_log.error("Router disconnected - firing notification events");
|
||||||
synchronized (listeners) {
|
synchronized (listeners) {
|
||||||
for (Iterator iter = listeners.iterator(); iter.hasNext();) {
|
for (Iterator iter = listeners.iterator(); iter.hasNext();) {
|
||||||
ConnectionEventListener lsnr = (ConnectionEventListener)iter.next();
|
ConnectionEventListener lsnr = (ConnectionEventListener) iter.next();
|
||||||
if (lsnr != null)
|
if (lsnr != null) lsnr.routerDisconnected();
|
||||||
lsnr.routerDisconnected();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -986,13 +965,39 @@ public class I2PTunnel implements Logging, EventDispatcher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Required by the EventDispatcher interface */
|
/* Required by the EventDispatcher interface */
|
||||||
public EventDispatcher getEventDispatcher() { return _event; }
|
public EventDispatcher getEventDispatcher() {
|
||||||
public void attachEventDispatcher(EventDispatcher e) { _event.attachEventDispatcher(e.getEventDispatcher()); }
|
return _event;
|
||||||
public void detachEventDispatcher(EventDispatcher e) { _event.detachEventDispatcher(e.getEventDispatcher()); }
|
}
|
||||||
public void notifyEvent(String e, Object a) { _event.notifyEvent(e,a); }
|
|
||||||
public Object getEventValue(String n) { return _event.getEventValue(n); }
|
public void attachEventDispatcher(EventDispatcher e) {
|
||||||
public Set getEvents() { return _event.getEvents(); }
|
_event.attachEventDispatcher(e.getEventDispatcher());
|
||||||
public void ignoreEvents() { _event.ignoreEvents(); }
|
}
|
||||||
public void unIgnoreEvents() { _event.unIgnoreEvents(); }
|
|
||||||
public Object waitEventValue(String n) { return _event.waitEventValue(n); }
|
public void detachEventDispatcher(EventDispatcher e) {
|
||||||
|
_event.detachEventDispatcher(e.getEventDispatcher());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void notifyEvent(String e, Object a) {
|
||||||
|
_event.notifyEvent(e, a);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object getEventValue(String n) {
|
||||||
|
return _event.getEventValue(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set getEvents() {
|
||||||
|
return _event.getEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ignoreEvents() {
|
||||||
|
_event.ignoreEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unIgnoreEvents() {
|
||||||
|
_event.unIgnoreEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object waitEventValue(String n) {
|
||||||
|
return _event.waitEventValue(n);
|
||||||
|
}
|
||||||
}
|
}
|
@ -18,9 +18,7 @@ public class I2PTunnelClient extends I2PTunnelClientBase {
|
|||||||
|
|
||||||
protected Destination dest;
|
protected Destination dest;
|
||||||
|
|
||||||
public I2PTunnelClient(int localPort, String destination,
|
public I2PTunnelClient(int localPort, String destination, Logging l, boolean ownDest, EventDispatcher notifyThis) {
|
||||||
Logging l, boolean ownDest,
|
|
||||||
EventDispatcher notifyThis) {
|
|
||||||
super(localPort, ownDest, l, notifyThis, "SynSender");
|
super(localPort, ownDest, l, notifyThis, "SynSender");
|
||||||
|
|
||||||
if (waitEventValue("openBaseClientResult").equals("error")) {
|
if (waitEventValue("openBaseClientResult").equals("error")) {
|
||||||
@ -29,7 +27,7 @@ public class I2PTunnelClient extends I2PTunnelClientBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
dest=I2PTunnel.destFromName(destination);
|
dest = I2PTunnel.destFromName(destination);
|
||||||
if (dest == null) {
|
if (dest == null) {
|
||||||
l.log("Could not resolve " + destination + ".");
|
l.log("Could not resolve " + destination + ".");
|
||||||
return;
|
return;
|
||||||
|
@ -23,13 +23,12 @@ import net.i2p.util.EventDispatcher;
|
|||||||
import net.i2p.util.I2PThread;
|
import net.i2p.util.I2PThread;
|
||||||
import net.i2p.util.Log;
|
import net.i2p.util.Log;
|
||||||
|
|
||||||
public abstract class I2PTunnelClientBase extends I2PTunnelTask
|
public abstract class I2PTunnelClientBase extends I2PTunnelTask implements Runnable {
|
||||||
implements Runnable {
|
|
||||||
|
|
||||||
private static final Log _log = new Log(I2PTunnelClientBase.class);
|
private static final Log _log = new Log(I2PTunnelClientBase.class);
|
||||||
protected Logging l;
|
protected Logging l;
|
||||||
|
|
||||||
private static final long DEFAULT_CONNECT_TIMEOUT = 60*1000;
|
private static final long DEFAULT_CONNECT_TIMEOUT = 60 * 1000;
|
||||||
|
|
||||||
protected Object sockLock = new Object(); // Guards sockMgr and mySockets
|
protected Object sockLock = new Object(); // Guards sockMgr and mySockets
|
||||||
private I2PSocketManager sockMgr;
|
private I2PSocketManager sockMgr;
|
||||||
@ -56,19 +55,17 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
|
|||||||
// I2PTunnelClientBase(localPort, ownDest, l, (EventDispatcher)null);
|
// I2PTunnelClientBase(localPort, ownDest, l, (EventDispatcher)null);
|
||||||
//}
|
//}
|
||||||
|
|
||||||
public I2PTunnelClientBase(int localPort, boolean ownDest,
|
public I2PTunnelClientBase(int localPort, boolean ownDest, Logging l, EventDispatcher notifyThis, String handlerName) {
|
||||||
Logging l, EventDispatcher notifyThis,
|
super(localPort + " (uninitialized)", notifyThis);
|
||||||
String handlerName) {
|
this.localPort = localPort;
|
||||||
super(localPort+" (uninitialized)", notifyThis);
|
|
||||||
this.localPort=localPort;
|
|
||||||
this.l = l;
|
this.l = l;
|
||||||
this.handlerName=handlerName;
|
this.handlerName = handlerName;
|
||||||
|
|
||||||
synchronized(sockLock) {
|
synchronized (sockLock) {
|
||||||
if (ownDest) {
|
if (ownDest) {
|
||||||
sockMgr=buildSocketManager();
|
sockMgr = buildSocketManager();
|
||||||
} else {
|
} else {
|
||||||
sockMgr=getSocketManager();
|
sockMgr = getSocketManager();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (sockMgr == null) throw new NullPointerException();
|
if (sockMgr == null) throw new NullPointerException();
|
||||||
@ -76,15 +73,14 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
|
|||||||
|
|
||||||
Thread t = new I2PThread(this);
|
Thread t = new I2PThread(this);
|
||||||
t.setName("Client");
|
t.setName("Client");
|
||||||
listenerReady=false;
|
listenerReady = false;
|
||||||
t.start();
|
t.start();
|
||||||
open=true;
|
open = true;
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
while (!listenerReady) {
|
while (!listenerReady) {
|
||||||
try {
|
try {
|
||||||
wait();
|
wait();
|
||||||
}
|
} catch (InterruptedException e) {
|
||||||
catch (InterruptedException e) {
|
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -111,8 +107,7 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
|
|||||||
protected static I2PSocketManager buildSocketManager() {
|
protected static I2PSocketManager buildSocketManager() {
|
||||||
Properties props = new Properties();
|
Properties props = new Properties();
|
||||||
props.putAll(System.getProperties());
|
props.putAll(System.getProperties());
|
||||||
return I2PSocketManagerFactory.createManager
|
return I2PSocketManagerFactory.createManager(I2PTunnel.host, Integer.parseInt(I2PTunnel.port), props);
|
||||||
(I2PTunnel.host, Integer.parseInt(I2PTunnel.port), props);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public final int getLocalPort() {
|
public final int getLocalPort() {
|
||||||
@ -123,8 +118,7 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
|
|||||||
try {
|
try {
|
||||||
return InetAddress.getByName(I2PTunnel.listenHost);
|
return InetAddress.getByName(I2PTunnel.listenHost);
|
||||||
} catch (UnknownHostException uhe) {
|
} catch (UnknownHostException uhe) {
|
||||||
l.log("Could not find listen host to bind to [" +
|
l.log("Could not find listen host to bind to [" + I2PTunnel.host + "]");
|
||||||
I2PTunnel.host + "]");
|
|
||||||
_log.error("Error finding host to bind", uhe);
|
_log.error("Error finding host to bind", uhe);
|
||||||
notifyEvent("openBaseClientResult", "error");
|
notifyEvent("openBaseClientResult", "error");
|
||||||
return null;
|
return null;
|
||||||
@ -196,11 +190,10 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
|
|||||||
localPort = ss.getLocalPort();
|
localPort = ss.getLocalPort();
|
||||||
}
|
}
|
||||||
notifyEvent("clientLocalPort", new Integer(ss.getLocalPort()));
|
notifyEvent("clientLocalPort", new Integer(ss.getLocalPort()));
|
||||||
l.log("Listening for clients on port " + localPort +
|
l.log("Listening for clients on port " + localPort + " of " + I2PTunnel.listenHost);
|
||||||
" of " + I2PTunnel.listenHost);
|
|
||||||
|
|
||||||
// Notify constructor that port is ready
|
// Notify constructor that port is ready
|
||||||
synchronized(this) {
|
synchronized (this) {
|
||||||
listenerReady = true;
|
listenerReady = true;
|
||||||
notify();
|
notify();
|
||||||
}
|
}
|
||||||
@ -210,7 +203,8 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
|
|||||||
while (!startRunning) {
|
while (!startRunning) {
|
||||||
try {
|
try {
|
||||||
startLock.wait();
|
startLock.wait();
|
||||||
} catch (InterruptedException ie) {}
|
} catch (InterruptedException ie) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -233,24 +227,23 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
|
|||||||
new ClientConnectionRunner(s, handlerName);
|
new ClientConnectionRunner(s, handlerName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public boolean close(boolean forced) {
|
public boolean close(boolean forced) {
|
||||||
if (!open) return true;
|
if (!open) return true;
|
||||||
// FIXME: here we might have to wait quite a long time if
|
// FIXME: here we might have to wait quite a long time if
|
||||||
// there is a connection attempt atm. But without waiting we
|
// there is a connection attempt atm. But without waiting we
|
||||||
// might risk to create an orphan socket. Would be better
|
// might risk to create an orphan socket. Would be better
|
||||||
// to return with an error in that situation quickly.
|
// to return with an error in that situation quickly.
|
||||||
synchronized(sockLock) {
|
synchronized (sockLock) {
|
||||||
mySockets.retainAll(sockMgr.listSockets());
|
mySockets.retainAll(sockMgr.listSockets());
|
||||||
if (!forced && mySockets.size() != 0) {
|
if (!forced && mySockets.size() != 0) {
|
||||||
l.log("There are still active connections!");
|
l.log("There are still active connections!");
|
||||||
_log.debug("can't close: there are still active connections!");
|
_log.debug("can't close: there are still active connections!");
|
||||||
for (Iterator it = mySockets.iterator(); it.hasNext();) {
|
for (Iterator it = mySockets.iterator(); it.hasNext();) {
|
||||||
l.log("->"+it.next());
|
l.log("->" + it.next());
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
l.log("Closing client "+toString());
|
l.log("Closing client " + toString());
|
||||||
try {
|
try {
|
||||||
if (ss != null) ss.close();
|
if (ss != null) ss.close();
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
@ -258,7 +251,7 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
l.log("Client closed.");
|
l.log("Client closed.");
|
||||||
open=false;
|
open = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -275,7 +268,7 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
|
|||||||
private Socket s;
|
private Socket s;
|
||||||
|
|
||||||
public ClientConnectionRunner(Socket s, String name) {
|
public ClientConnectionRunner(Socket s, String name) {
|
||||||
this.s=s;
|
this.s = s;
|
||||||
setName(name);
|
setName(name);
|
||||||
start();
|
start();
|
||||||
}
|
}
|
||||||
|
@ -22,12 +22,12 @@ public class I2PTunnelGUI extends Frame implements ActionListener, Logging {
|
|||||||
|
|
||||||
public I2PTunnelGUI(I2PTunnel t) {
|
public I2PTunnelGUI(I2PTunnel t) {
|
||||||
super("I2PTunnel control panel");
|
super("I2PTunnel control panel");
|
||||||
this.t=t;
|
this.t = t;
|
||||||
setLayout(new BorderLayout());
|
setLayout(new BorderLayout());
|
||||||
add("South", input=new TextField());
|
add("South", input = new TextField());
|
||||||
input.addActionListener(this);
|
input.addActionListener(this);
|
||||||
Font font = new Font("Monospaced",Font.PLAIN,12);
|
Font font = new Font("Monospaced", Font.PLAIN, 12);
|
||||||
add("Center",log=new TextArea("",20,80,TextArea.SCROLLBARS_VERTICAL_ONLY));
|
add("Center", log = new TextArea("", 20, 80, TextArea.SCROLLBARS_VERTICAL_ONLY));
|
||||||
log.setFont(font);
|
log.setFont(font);
|
||||||
log.setEditable(false);
|
log.setEditable(false);
|
||||||
log("enter 'help' for help.");
|
log("enter 'help' for help.");
|
||||||
@ -36,11 +36,11 @@ public class I2PTunnelGUI extends Frame implements ActionListener, Logging {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void log(String s) {
|
public void log(String s) {
|
||||||
log.append(s+"\n");
|
log.append(s + "\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void actionPerformed(ActionEvent evt) {
|
public void actionPerformed(ActionEvent evt) {
|
||||||
log("I2PTunnel>"+input.getText());
|
log("I2PTunnel>" + input.getText());
|
||||||
t.runCommand(input.getText(), this);
|
t.runCommand(input.getText(), this);
|
||||||
log("---");
|
log("---");
|
||||||
input.setText("");
|
input.setText("");
|
||||||
|
@ -19,16 +19,17 @@ import net.i2p.util.EventDispatcher;
|
|||||||
import net.i2p.util.I2PThread;
|
import net.i2p.util.I2PThread;
|
||||||
import net.i2p.util.Log;
|
import net.i2p.util.Log;
|
||||||
|
|
||||||
public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
public class I2PTunnelHTTPClient extends I2PTunnelClientBase implements Runnable {
|
||||||
implements Runnable {
|
private static final Log _log = new Log(I2PTunnelHTTPClient.class);
|
||||||
private static final Log _log =
|
|
||||||
new Log(I2PTunnelHTTPClient.class);
|
|
||||||
|
|
||||||
private String wwwProxy;
|
private String wwwProxy;
|
||||||
|
|
||||||
private final static byte[] ERR_REQUEST_DENIED = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=iso-8859-1\r\nCache-control: no-cache\r\n\r\n<html><body><H1>I2P ERROR: REQUEST DENIED</H1>You attempted to connect to a non-I2P website or location.<BR>".getBytes();
|
private final static byte[] ERR_REQUEST_DENIED = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=iso-8859-1\r\nCache-control: no-cache\r\n\r\n<html><body><H1>I2P ERROR: REQUEST DENIED</H1>You attempted to connect to a non-I2P website or location.<BR>"
|
||||||
private final static byte[] ERR_DESTINATION_UNKNOWN = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=iso-8859-1\r\nCache-control: no-cache\r\n\r\n<html><body><H1>I2P ERROR: NOT FOUND</H1>That Desitination was not found. Perhaps you pasted in the wrong BASE64 I2P Destination or the link you are following is bad. The host (or the WWW proxy, if you're using one) could also be temporarily offline. Could not find the following Destination:<BR><BR>".getBytes();
|
.getBytes();
|
||||||
private final static byte[] ERR_TIMEOUT = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=iso-8859-1\r\nCache-control: no-cache\r\n\r\n<html><body><H1>I2P ERROR: TIMEOUT</H1>That Desitination was reachable, but timed out getting a response. This may be a temporary error, so you should simply try to refresh, though if the problem persists, the remote destination may have issues. Could not get a response from the following Destination:<BR><BR>".getBytes();
|
private final static byte[] ERR_DESTINATION_UNKNOWN = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=iso-8859-1\r\nCache-control: no-cache\r\n\r\n<html><body><H1>I2P ERROR: NOT FOUND</H1>That Desitination was not found. Perhaps you pasted in the wrong BASE64 I2P Destination or the link you are following is bad. The host (or the WWW proxy, if you're using one) could also be temporarily offline. Could not find the following Destination:<BR><BR>"
|
||||||
|
.getBytes();
|
||||||
|
private final static byte[] ERR_TIMEOUT = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=iso-8859-1\r\nCache-control: no-cache\r\n\r\n<html><body><H1>I2P ERROR: TIMEOUT</H1>That Desitination was reachable, but timed out getting a response. This may be a temporary error, so you should simply try to refresh, though if the problem persists, the remote destination may have issues. Could not get a response from the following Destination:<BR><BR>"
|
||||||
|
.getBytes();
|
||||||
|
|
||||||
//public I2PTunnelHTTPClient(int localPort, Logging l,
|
//public I2PTunnelHTTPClient(int localPort, Logging l,
|
||||||
// boolean ownDest,
|
// boolean ownDest,
|
||||||
@ -37,9 +38,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
// (EventDispatcher)null);
|
// (EventDispatcher)null);
|
||||||
//}
|
//}
|
||||||
|
|
||||||
public I2PTunnelHTTPClient(int localPort, Logging l,
|
public I2PTunnelHTTPClient(int localPort, Logging l, boolean ownDest, String wwwProxy, EventDispatcher notifyThis) {
|
||||||
boolean ownDest,
|
|
||||||
String wwwProxy, EventDispatcher notifyThis) {
|
|
||||||
super(localPort, ownDest, l, notifyThis, "HTTPHandler");
|
super(localPort, ownDest, l, notifyThis, "HTTPHandler");
|
||||||
|
|
||||||
if (waitEventValue("openBaseClientResult").equals("error")) {
|
if (waitEventValue("openBaseClientResult").equals("error")) {
|
||||||
@ -49,8 +48,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
|
|
||||||
this.wwwProxy = wwwProxy;
|
this.wwwProxy = wwwProxy;
|
||||||
|
|
||||||
setName(getLocalPort()
|
setName(getLocalPort() + " -> HTTPClient [WWW outproxy: " + this.wwwProxy + "]");
|
||||||
+ " -> HTTPClient [WWW outproxy: " + this.wwwProxy + "]");
|
|
||||||
|
|
||||||
startRunning();
|
startRunning();
|
||||||
|
|
||||||
@ -64,90 +62,83 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
InactivityTimeoutThread timeoutThread = null;
|
InactivityTimeoutThread timeoutThread = null;
|
||||||
try {
|
try {
|
||||||
out = s.getOutputStream();
|
out = s.getOutputStream();
|
||||||
BufferedReader br = new BufferedReader
|
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream(), "ISO-8859-1"));
|
||||||
(new InputStreamReader(s.getInputStream(),
|
String line, method = null, protocol = null, host = null, destination = null;
|
||||||
"ISO-8859-1"));
|
StringBuffer newRequest = new StringBuffer();
|
||||||
String line, method=null, protocol=null, host=null, destination=null;
|
while ((line = br.readLine()) != null) {
|
||||||
StringBuffer newRequest=new StringBuffer();
|
if (method == null) { // first line (GET /base64/realaddr)
|
||||||
while ((line=br.readLine()) != null) {
|
int pos = line.indexOf(" ");
|
||||||
if (method==null) { // first line (GET /base64/realaddr)
|
|
||||||
int pos=line.indexOf(" ");
|
|
||||||
if (pos == -1) break;
|
if (pos == -1) break;
|
||||||
method=line.substring(0, pos);
|
method = line.substring(0, pos);
|
||||||
String request = line.substring(pos+1);
|
String request = line.substring(pos + 1);
|
||||||
if (request.startsWith("/") &&
|
if (request.startsWith("/") && System.getProperty("i2ptunnel.noproxy") != null) {
|
||||||
System.getProperty("i2ptunnel.noproxy") != null) {
|
request = "http://i2p" + request;
|
||||||
request="http://i2p"+request;
|
|
||||||
}
|
}
|
||||||
pos = request.indexOf("//");
|
pos = request.indexOf("//");
|
||||||
if (pos == -1) {
|
if (pos == -1) {
|
||||||
method=null;
|
method = null;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
protocol=request.substring(0,pos+2);
|
protocol = request.substring(0, pos + 2);
|
||||||
request=request.substring(pos+2);
|
request = request.substring(pos + 2);
|
||||||
|
|
||||||
targetRequest = request;
|
targetRequest = request;
|
||||||
|
|
||||||
pos = request.indexOf("/");
|
pos = request.indexOf("/");
|
||||||
if (pos == -1) {
|
if (pos == -1) {
|
||||||
method=null;
|
method = null;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
host=request.substring(0,pos);
|
host = request.substring(0, pos);
|
||||||
|
|
||||||
// Quick hack for foo.bar.i2p
|
// Quick hack for foo.bar.i2p
|
||||||
if (host.toLowerCase().endsWith( ".i2p")) {
|
if (host.toLowerCase().endsWith(".i2p")) {
|
||||||
destination=host;
|
destination = host;
|
||||||
host=getHostName(destination);
|
host = getHostName(destination);
|
||||||
line=method+" "+request.substring(pos);
|
line = method + " " + request.substring(pos);
|
||||||
} else if (host.indexOf(".") != -1) {
|
} else if (host.indexOf(".") != -1) {
|
||||||
// The request must be forwarded to a WWW proxy
|
// The request must be forwarded to a WWW proxy
|
||||||
destination = wwwProxy;
|
destination = wwwProxy;
|
||||||
usingWWWProxy = true;
|
usingWWWProxy = true;
|
||||||
} else {
|
} else {
|
||||||
request=request.substring(pos+1);
|
request = request.substring(pos + 1);
|
||||||
pos = request.indexOf("/");
|
pos = request.indexOf("/");
|
||||||
destination=request.substring(0,pos);
|
destination = request.substring(0, pos);
|
||||||
line=method+" "+request.substring(pos);
|
line = method + " " + request.substring(pos);
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean isValid = usingWWWProxy ||
|
boolean isValid = usingWWWProxy || isSupportedAddress(host, protocol);
|
||||||
isSupportedAddress(host, protocol);
|
|
||||||
if (!isValid) {
|
if (!isValid) {
|
||||||
if (_log.shouldLog(Log.INFO))
|
if (_log.shouldLog(Log.INFO)) _log.info("notValid(" + host + ")");
|
||||||
_log.info("notValid(" + host + ")");
|
method = null;
|
||||||
method=null;
|
destination = null;
|
||||||
destination=null;
|
|
||||||
break;
|
break;
|
||||||
} else if (!usingWWWProxy) {
|
} else if (!usingWWWProxy) {
|
||||||
if (_log.shouldLog(Log.INFO))
|
if (_log.shouldLog(Log.INFO)) _log.info("host=getHostName(" + destination + ")");
|
||||||
_log.info("host=getHostName(" + destination + ")");
|
host = getHostName(destination); // hide original host
|
||||||
host=getHostName(destination); // hide original host
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_log.shouldLog(Log.DEBUG)) {
|
if (_log.shouldLog(Log.DEBUG)) {
|
||||||
_log.debug("METHOD:"+method+":");
|
_log.debug("METHOD:" + method + ":");
|
||||||
_log.debug("PROTOC:"+protocol+":");
|
_log.debug("PROTOC:" + protocol + ":");
|
||||||
_log.debug("HOST :"+host+":");
|
_log.debug("HOST :" + host + ":");
|
||||||
_log.debug("DEST :"+destination+":");
|
_log.debug("DEST :" + destination + ":");
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (line.startsWith("Host: ") && !usingWWWProxy) {
|
} else if (line.startsWith("Host: ") && !usingWWWProxy) {
|
||||||
line="Host: "+host;
|
line = "Host: " + host;
|
||||||
if (_log.shouldLog(Log.INFO))
|
if (_log.shouldLog(Log.INFO)) _log.info("Setting host = " + host);
|
||||||
_log.info("Setting host = " + host);
|
|
||||||
}
|
}
|
||||||
newRequest.append(line).append("\r\n"); // HTTP spec
|
newRequest.append(line).append("\r\n"); // HTTP spec
|
||||||
if (line.length()==0) break;
|
if (line.length() == 0) break;
|
||||||
}
|
}
|
||||||
while (br.ready()) { // empty the buffer (POST requests)
|
while (br.ready()) { // empty the buffer (POST requests)
|
||||||
int i=br.read();
|
int i = br.read();
|
||||||
if (i != -1) {
|
if (i != -1) {
|
||||||
newRequest.append((char)i);
|
newRequest.append((char) i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (method==null || destination==null) {
|
if (method == null || destination == null) {
|
||||||
l.log("No HTTP method found in the request.");
|
l.log("No HTTP method found in the request.");
|
||||||
if (out != null) {
|
if (out != null) {
|
||||||
out.write(ERR_REQUEST_DENIED);
|
out.write(ERR_REQUEST_DENIED);
|
||||||
@ -159,37 +150,34 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
s.close();
|
s.close();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Destination dest=I2PTunnel.destFromName(destination);
|
Destination dest = I2PTunnel.destFromName(destination);
|
||||||
if (dest == null) {
|
if (dest == null) {
|
||||||
l.log("Could not resolve "+destination+".");
|
l.log("Could not resolve " + destination + ".");
|
||||||
writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest,
|
writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest, usingWWWProxy, destination);
|
||||||
usingWWWProxy, destination);
|
|
||||||
s.close();
|
s.close();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String remoteID;
|
String remoteID;
|
||||||
I2PSocket i2ps = createI2PSocket(dest);
|
I2PSocket i2ps = createI2PSocket(dest);
|
||||||
byte[] data=newRequest.toString().getBytes("ISO-8859-1");
|
byte[] data = newRequest.toString().getBytes("ISO-8859-1");
|
||||||
I2PTunnelRunner runner = new I2PTunnelRunner(s, i2ps, sockLock, data);
|
I2PTunnelRunner runner = new I2PTunnelRunner(s, i2ps, sockLock, data);
|
||||||
timeoutThread = new InactivityTimeoutThread(runner, out, targetRequest, usingWWWProxy, s);
|
timeoutThread = new InactivityTimeoutThread(runner, out, targetRequest, usingWWWProxy, s);
|
||||||
timeoutThread.start();
|
timeoutThread.start();
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
if (timeoutThread != null) timeoutThread.disable();
|
if (timeoutThread != null) timeoutThread.disable();
|
||||||
_log.error("Error sending syn", ex);
|
_log.error("Error sending syn", ex);
|
||||||
handleHTTPClientException(ex, out, targetRequest,
|
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, wwwProxy);
|
||||||
usingWWWProxy, wwwProxy);
|
|
||||||
closeSocket(s);
|
closeSocket(s);
|
||||||
} catch (I2PException ex) {
|
} catch (I2PException ex) {
|
||||||
if (timeoutThread != null) timeoutThread.disable();
|
if (timeoutThread != null) timeoutThread.disable();
|
||||||
_log.info("Error sending syn", ex);
|
_log.info("Error sending syn", ex);
|
||||||
l.log("Unable to reach peer");
|
l.log("Unable to reach peer");
|
||||||
handleHTTPClientException(ex, out, targetRequest,
|
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, wwwProxy);
|
||||||
usingWWWProxy, wwwProxy);
|
|
||||||
closeSocket(s);
|
closeSocket(s);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final long INACTIVITY_TIMEOUT = 120*1000;
|
private static final long INACTIVITY_TIMEOUT = 120 * 1000;
|
||||||
|
|
||||||
private class InactivityTimeoutThread extends I2PThread {
|
private class InactivityTimeoutThread extends I2PThread {
|
||||||
|
|
||||||
@ -201,8 +189,9 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
private boolean _disabled;
|
private boolean _disabled;
|
||||||
private Object _disableLock = new Object();
|
private Object _disableLock = new Object();
|
||||||
|
|
||||||
public InactivityTimeoutThread(I2PTunnelRunner runner, OutputStream out, String targetRequest, boolean useWWWProxy, Socket s) {
|
public InactivityTimeoutThread(I2PTunnelRunner runner, OutputStream out, String targetRequest,
|
||||||
this.s=s;
|
boolean useWWWProxy, Socket s) {
|
||||||
|
this.s = s;
|
||||||
_runner = runner;
|
_runner = runner;
|
||||||
_out = out;
|
_out = out;
|
||||||
_targetRequest = targetRequest;
|
_targetRequest = targetRequest;
|
||||||
@ -210,21 +199,26 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
_disabled = false;
|
_disabled = false;
|
||||||
setName("InactivityThread");
|
setName("InactivityThread");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void disable() {
|
public void disable() {
|
||||||
_disabled = true;
|
_disabled = true;
|
||||||
synchronized (_disableLock) { _disableLock.notifyAll(); }
|
synchronized (_disableLock) {
|
||||||
|
_disableLock.notifyAll();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
while (!_disabled) {
|
while (!_disabled) {
|
||||||
if (_runner.isFinished()) {
|
if (_runner.isFinished()) {
|
||||||
if (_log.shouldLog(Log.INFO))
|
if (_log.shouldLog(Log.INFO)) _log.info("HTTP client request completed prior to timeout");
|
||||||
_log.info("HTTP client request completed prior to timeout");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (_runner.getLastActivityOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {
|
if (_runner.getLastActivityOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {
|
||||||
if (_runner.getStartedOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {
|
if (_runner.getStartedOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {
|
||||||
if (_log.shouldLog(Log.WARN))
|
if (_log.shouldLog(Log.WARN))
|
||||||
_log.warn("HTTP client request timed out (lastActivity: " + new Date(_runner.getLastActivityOn()) + ", startedOn: " + new Date(_runner.getLastActivityOn()) + ")");
|
_log.warn("HTTP client request timed out (lastActivity: "
|
||||||
|
+ new Date(_runner.getLastActivityOn()) + ", startedOn: "
|
||||||
|
+ new Date(_runner.getLastActivityOn()) + ")");
|
||||||
timeout();
|
timeout();
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
@ -236,10 +230,12 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
synchronized (_disableLock) {
|
synchronized (_disableLock) {
|
||||||
try {
|
try {
|
||||||
_disableLock.wait(INACTIVITY_TIMEOUT);
|
_disableLock.wait(INACTIVITY_TIMEOUT);
|
||||||
} catch (InterruptedException ie) {}
|
} catch (InterruptedException ie) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void timeout() {
|
private void timeout() {
|
||||||
_log.info("Inactivity timeout reached");
|
_log.info("Inactivity timeout reached");
|
||||||
l.log("Inactivity timeout reached");
|
l.log("Inactivity timeout reached");
|
||||||
@ -248,8 +244,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
if (_runner.getLastActivityOn() > 0) {
|
if (_runner.getLastActivityOn() > 0) {
|
||||||
// some data has been sent, so don't 404 it
|
// some data has been sent, so don't 404 it
|
||||||
} else {
|
} else {
|
||||||
writeErrorMessage(ERR_TIMEOUT, _out, _targetRequest,
|
writeErrorMessage(ERR_TIMEOUT, _out, _targetRequest, _useWWWProxy, wwwProxy);
|
||||||
_useWWWProxy, wwwProxy);
|
|
||||||
}
|
}
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
_log.warn("Error writing out the 'timeout' message", ioe);
|
_log.warn("Error writing out the 'timeout' message", ioe);
|
||||||
@ -263,7 +258,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
|
|
||||||
private final static String getHostName(String host) {
|
private final static String getHostName(String host) {
|
||||||
try {
|
try {
|
||||||
Destination dest=I2PTunnel.destFromName(host);
|
Destination dest = I2PTunnel.destFromName(host);
|
||||||
if (dest == null) return "i2p";
|
if (dest == null) return "i2p";
|
||||||
return dest.toBase64();
|
return dest.toBase64();
|
||||||
} catch (DataFormatException dfe) {
|
} catch (DataFormatException dfe) {
|
||||||
@ -271,18 +266,13 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void writeErrorMessage(byte[] errMessage, OutputStream out,
|
private static void writeErrorMessage(byte[] errMessage, OutputStream out, String targetRequest,
|
||||||
String targetRequest,
|
boolean usingWWWProxy, String wwwProxy) throws IOException {
|
||||||
boolean usingWWWProxy,
|
|
||||||
String wwwProxy)
|
|
||||||
throws IOException {
|
|
||||||
if (out != null) {
|
if (out != null) {
|
||||||
out.write(errMessage);
|
out.write(errMessage);
|
||||||
if (targetRequest != null) {
|
if (targetRequest != null) {
|
||||||
out.write(targetRequest.getBytes());
|
out.write(targetRequest.getBytes());
|
||||||
if (usingWWWProxy)
|
if (usingWWWProxy) out.write(("<br>WWW proxy: " + wwwProxy).getBytes());
|
||||||
out.write(("<br>WWW proxy: " +
|
|
||||||
wwwProxy).getBytes());
|
|
||||||
}
|
}
|
||||||
out.write("<p /><i>Generated on: ".getBytes());
|
out.write("<p /><i>Generated on: ".getBytes());
|
||||||
out.write(new Date().toString().getBytes());
|
out.write(new Date().toString().getBytes());
|
||||||
@ -291,29 +281,23 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void handleHTTPClientException (Exception ex, OutputStream out,
|
private static void handleHTTPClientException(Exception ex, OutputStream out, String targetRequest,
|
||||||
String targetRequest,
|
boolean usingWWWProxy, String wwwProxy) {
|
||||||
boolean usingWWWProxy,
|
|
||||||
String wwwProxy) {
|
|
||||||
if (out != null) {
|
if (out != null) {
|
||||||
try {
|
try {
|
||||||
writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest,
|
writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest, usingWWWProxy, wwwProxy);
|
||||||
usingWWWProxy, wwwProxy);
|
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
_log.warn("Error writing out the 'destination was unknown' "+
|
_log.warn("Error writing out the 'destination was unknown' " + "message", ioe);
|
||||||
"message", ioe);
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
_log.warn("Client disconnected before we could say that destination "+
|
_log.warn("Client disconnected before we could say that destination " + "was unknown", ex);
|
||||||
"was unknown", ex);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private final static String SUPPORTED_HOSTS[] = { "i2p", "www.i2p.com",
|
private final static String SUPPORTED_HOSTS[] = { "i2p", "www.i2p.com", "i2p."};
|
||||||
"i2p." };
|
|
||||||
|
|
||||||
private boolean isSupportedAddress(String host, String protocol) {
|
private boolean isSupportedAddress(String host, String protocol) {
|
||||||
if ( (host == null) || (protocol == null) ) return false;
|
if ((host == null) || (protocol == null)) return false;
|
||||||
boolean found = false;
|
boolean found = false;
|
||||||
String lcHost = host.toLowerCase();
|
String lcHost = host.toLowerCase();
|
||||||
for (int i = 0; i < SUPPORTED_HOSTS.length; i++) {
|
for (int i = 0; i < SUPPORTED_HOSTS.length; i++) {
|
||||||
@ -327,7 +311,8 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
|
|||||||
try {
|
try {
|
||||||
Destination d = I2PTunnel.destFromName(host);
|
Destination d = I2PTunnel.destFromName(host);
|
||||||
if (d == null) return false;
|
if (d == null) return false;
|
||||||
} catch (DataFormatException dfe) {}
|
} catch (DataFormatException dfe) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return protocol.equalsIgnoreCase("http://");
|
return protocol.equalsIgnoreCase("http://");
|
||||||
|
@ -26,14 +26,14 @@ public class I2PTunnelRunner extends I2PThread {
|
|||||||
* Sun's impl of BufferedOutputStream), but that is the streaming
|
* Sun's impl of BufferedOutputStream), but that is the streaming
|
||||||
* api's job...
|
* api's job...
|
||||||
*/
|
*/
|
||||||
static int MAX_PACKET_SIZE = 1024*32;
|
static int MAX_PACKET_SIZE = 1024 * 32;
|
||||||
|
|
||||||
static final int NETWORK_BUFFER_SIZE = MAX_PACKET_SIZE;
|
static final int NETWORK_BUFFER_SIZE = MAX_PACKET_SIZE;
|
||||||
|
|
||||||
private Socket s;
|
private Socket s;
|
||||||
private I2PSocket i2ps;
|
private I2PSocket i2ps;
|
||||||
Object slock, finishLock = new Object();
|
Object slock, finishLock = new Object();
|
||||||
boolean finished=false;
|
boolean finished = false;
|
||||||
HashMap ostreams, sockets;
|
HashMap ostreams, sockets;
|
||||||
I2PSession session;
|
I2PSession session;
|
||||||
byte[] initialData;
|
byte[] initialData;
|
||||||
@ -42,11 +42,10 @@ public class I2PTunnelRunner extends I2PThread {
|
|||||||
/** when the runner started up */
|
/** when the runner started up */
|
||||||
private long startedOn;
|
private long startedOn;
|
||||||
|
|
||||||
public I2PTunnelRunner(Socket s, I2PSocket i2ps, Object slock,
|
public I2PTunnelRunner(Socket s, I2PSocket i2ps, Object slock, byte[] initialData) {
|
||||||
byte[] initialData) {
|
this.s = s;
|
||||||
this.s=s;
|
this.i2ps = i2ps;
|
||||||
this.i2ps=i2ps;
|
this.slock = slock;
|
||||||
this.slock=slock;
|
|
||||||
this.initialData = initialData;
|
this.initialData = initialData;
|
||||||
lastActivityOn = -1;
|
lastActivityOn = -1;
|
||||||
startedOn = -1;
|
startedOn = -1;
|
||||||
@ -60,7 +59,9 @@ public class I2PTunnelRunner extends I2PThread {
|
|||||||
* [aka we're done running the streams]?
|
* [aka we're done running the streams]?
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public boolean isFinished() { return finished; }
|
public boolean isFinished() {
|
||||||
|
return finished;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* When was the last data for this runner sent or received?
|
* When was the last data for this runner sent or received?
|
||||||
@ -68,33 +69,38 @@ public class I2PTunnelRunner extends I2PThread {
|
|||||||
* @return date (ms since the epoch), or -1 if no data has been transferred yet
|
* @return date (ms since the epoch), or -1 if no data has been transferred yet
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public long getLastActivityOn() { return lastActivityOn; }
|
public long getLastActivityOn() {
|
||||||
private void updateActivity() { lastActivityOn = Clock.getInstance().now(); }
|
return lastActivityOn;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateActivity() {
|
||||||
|
lastActivityOn = Clock.getInstance().now();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* When this runner started up transferring data
|
* When this runner started up transferring data
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public long getStartedOn() { return startedOn; }
|
public long getStartedOn() {
|
||||||
|
return startedOn;
|
||||||
|
}
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
startedOn = Clock.getInstance().now();
|
startedOn = Clock.getInstance().now();
|
||||||
try {
|
try {
|
||||||
InputStream in = s.getInputStream();
|
InputStream in = s.getInputStream();
|
||||||
OutputStream out = new BufferedOutputStream(s.getOutputStream(),
|
OutputStream out = new BufferedOutputStream(s.getOutputStream(), NETWORK_BUFFER_SIZE);
|
||||||
NETWORK_BUFFER_SIZE);
|
|
||||||
InputStream i2pin = i2ps.getInputStream();
|
InputStream i2pin = i2ps.getInputStream();
|
||||||
OutputStream i2pout = new BufferedOutputStream
|
OutputStream i2pout = new BufferedOutputStream(i2ps.getOutputStream(), MAX_PACKET_SIZE);
|
||||||
(i2ps.getOutputStream(), MAX_PACKET_SIZE);
|
|
||||||
if (initialData != null) {
|
if (initialData != null) {
|
||||||
synchronized(slock) {
|
synchronized (slock) {
|
||||||
i2pout.write(initialData);
|
i2pout.write(initialData);
|
||||||
i2pout.flush();
|
i2pout.flush();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Thread t1 = new StreamForwarder(in, i2pout);
|
Thread t1 = new StreamForwarder(in, i2pout);
|
||||||
Thread t2 = new StreamForwarder(i2pin, out);
|
Thread t2 = new StreamForwarder(i2pin, out);
|
||||||
synchronized(finishLock) {
|
synchronized (finishLock) {
|
||||||
while (!finished) {
|
while (!finished) {
|
||||||
finishLock.wait();
|
finishLock.wait();
|
||||||
}
|
}
|
||||||
@ -128,8 +134,8 @@ public class I2PTunnelRunner extends I2PThread {
|
|||||||
OutputStream out;
|
OutputStream out;
|
||||||
|
|
||||||
private StreamForwarder(InputStream in, OutputStream out) {
|
private StreamForwarder(InputStream in, OutputStream out) {
|
||||||
this.in=in;
|
this.in = in;
|
||||||
this.out=out;
|
this.out = out;
|
||||||
setName("StreamForwarder");
|
setName("StreamForwarder");
|
||||||
start();
|
start();
|
||||||
}
|
}
|
||||||
@ -138,26 +144,25 @@ public class I2PTunnelRunner extends I2PThread {
|
|||||||
byte[] buffer = new byte[NETWORK_BUFFER_SIZE];
|
byte[] buffer = new byte[NETWORK_BUFFER_SIZE];
|
||||||
try {
|
try {
|
||||||
int len;
|
int len;
|
||||||
while ((len=in.read(buffer)) != -1) {
|
while ((len = in.read(buffer)) != -1) {
|
||||||
out.write(buffer, 0, len);
|
out.write(buffer, 0, len);
|
||||||
|
|
||||||
if (len > 0)
|
if (len > 0) updateActivity();
|
||||||
updateActivity();
|
|
||||||
|
|
||||||
if (in.available()==0) {
|
if (in.available() == 0) {
|
||||||
try {
|
try {
|
||||||
Thread.sleep(I2PTunnel.PACKET_DELAY);
|
Thread.sleep(I2PTunnel.PACKET_DELAY);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (in.available()==0) {
|
if (in.available() == 0) {
|
||||||
out.flush(); // make sure the data get though
|
out.flush(); // make sure the data get though
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (SocketException ex) {
|
} catch (SocketException ex) {
|
||||||
// this *will* occur when the other threads closes the socket
|
// this *will* occur when the other threads closes the socket
|
||||||
synchronized(finishLock) {
|
synchronized (finishLock) {
|
||||||
if (!finished)
|
if (!finished)
|
||||||
_log.error("Error reading and writing", ex);
|
_log.error("Error reading and writing", ex);
|
||||||
else
|
else
|
||||||
@ -175,8 +180,8 @@ public class I2PTunnelRunner extends I2PThread {
|
|||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
_log.error("Error closing streams", ex);
|
_log.error("Error closing streams", ex);
|
||||||
}
|
}
|
||||||
synchronized(finishLock) {
|
synchronized (finishLock) {
|
||||||
finished=true;
|
finished = true;
|
||||||
finishLock.notifyAll();
|
finishLock.notifyAll();
|
||||||
// the main thread will close sockets etc. now
|
// the main thread will close sockets etc. now
|
||||||
}
|
}
|
||||||
|
@ -26,8 +26,7 @@ import net.i2p.util.EventDispatcher;
|
|||||||
import net.i2p.util.I2PThread;
|
import net.i2p.util.I2PThread;
|
||||||
import net.i2p.util.Log;
|
import net.i2p.util.Log;
|
||||||
|
|
||||||
public class I2PTunnelServer extends I2PTunnelTask
|
public class I2PTunnelServer extends I2PTunnelTask implements Runnable {
|
||||||
implements Runnable {
|
|
||||||
|
|
||||||
private final static Log _log = new Log(I2PTunnelServer.class);
|
private final static Log _log = new Log(I2PTunnelServer.class);
|
||||||
|
|
||||||
@ -41,18 +40,15 @@ public class I2PTunnelServer extends I2PTunnelTask
|
|||||||
|
|
||||||
private Logging l;
|
private Logging l;
|
||||||
|
|
||||||
public I2PTunnelServer(InetAddress host, int port,
|
public I2PTunnelServer(InetAddress host, int port, String privData, Logging l, EventDispatcher notifyThis) {
|
||||||
String privData, Logging l,
|
super(host + ":" + port + " <- " + privData, notifyThis);
|
||||||
EventDispatcher notifyThis) {
|
|
||||||
super(host+":"+port+" <- "+privData, notifyThis);
|
|
||||||
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(privData));
|
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(privData));
|
||||||
init(host, port, bais, privData, l);
|
init(host, port, bais, privData, l);
|
||||||
}
|
}
|
||||||
|
|
||||||
public I2PTunnelServer(InetAddress host, int port,
|
public I2PTunnelServer(InetAddress host, int port, File privkey, String privkeyname, Logging l,
|
||||||
File privkey, String privkeyname,
|
EventDispatcher notifyThis) {
|
||||||
Logging l, EventDispatcher notifyThis) {
|
super(host + ":" + port + " <- " + privkeyname, notifyThis);
|
||||||
super(host+":"+port+" <- "+privkeyname, notifyThis);
|
|
||||||
try {
|
try {
|
||||||
init(host, port, new FileInputStream(privkey), privkeyname, l);
|
init(host, port, new FileInputStream(privkey), privkeyname, l);
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
@ -60,48 +56,44 @@ public class I2PTunnelServer extends I2PTunnelTask
|
|||||||
notifyEvent("openServerResult", "error");
|
notifyEvent("openServerResult", "error");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public I2PTunnelServer(InetAddress host, int port,
|
|
||||||
InputStream privData, String privkeyname,
|
public I2PTunnelServer(InetAddress host, int port, InputStream privData, String privkeyname, Logging l,
|
||||||
Logging l, EventDispatcher notifyThis) {
|
EventDispatcher notifyThis) {
|
||||||
super(host+":"+port+" <- "+privkeyname, notifyThis);
|
super(host + ":" + port + " <- " + privkeyname, notifyThis);
|
||||||
init(host, port, privData, privkeyname, l);
|
init(host, port, privData, privkeyname, l);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void init(InetAddress host, int port, InputStream privData,
|
private void init(InetAddress host, int port, InputStream privData, String privkeyname, Logging l) {
|
||||||
String privkeyname, Logging l) {
|
this.l = l;
|
||||||
this.l=l;
|
this.remoteHost = host;
|
||||||
this.remoteHost=host;
|
this.remotePort = port;
|
||||||
this.remotePort=port;
|
|
||||||
I2PClient client = I2PClientFactory.createClient();
|
I2PClient client = I2PClientFactory.createClient();
|
||||||
Properties props = new Properties();
|
Properties props = new Properties();
|
||||||
props.putAll(System.getProperties());
|
props.putAll(System.getProperties());
|
||||||
synchronized(slock) {
|
synchronized (slock) {
|
||||||
sockMgr = I2PSocketManagerFactory.createManager
|
sockMgr = I2PSocketManagerFactory.createManager(privData, I2PTunnel.host, Integer.parseInt(I2PTunnel.port),
|
||||||
(privData, I2PTunnel.host,
|
props);
|
||||||
Integer.parseInt(I2PTunnel.port), props);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
l.log("Ready!");
|
l.log("Ready!");
|
||||||
notifyEvent("openServerResult", "ok");
|
notifyEvent("openServerResult", "ok");
|
||||||
open=true;
|
open = true;
|
||||||
Thread t = new I2PThread(this);
|
Thread t = new I2PThread(this);
|
||||||
t.setName("Server");
|
t.setName("Server");
|
||||||
t.start();
|
t.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public boolean close(boolean forced) {
|
public boolean close(boolean forced) {
|
||||||
if (!open) return true;
|
if (!open) return true;
|
||||||
synchronized(lock) {
|
synchronized (lock) {
|
||||||
if (!forced && sockMgr.listSockets().size() != 0) {
|
if (!forced && sockMgr.listSockets().size() != 0) {
|
||||||
l.log("There are still active connections!");
|
l.log("There are still active connections!");
|
||||||
for (Iterator it = sockMgr.listSockets().iterator();
|
for (Iterator it = sockMgr.listSockets().iterator(); it.hasNext();) {
|
||||||
it.hasNext();) {
|
l.log("->" + it.next());
|
||||||
l.log("->"+it.next());
|
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
l.log("Shutting down server "+toString());
|
l.log("Shutting down server " + toString());
|
||||||
try {
|
try {
|
||||||
if (i2pss != null) i2pss.close();
|
if (i2pss != null) i2pss.close();
|
||||||
sockMgr.getSession().destroySession();
|
sockMgr.getSession().destroySession();
|
||||||
@ -110,12 +102,11 @@ public class I2PTunnelServer extends I2PTunnelTask
|
|||||||
System.exit(1);
|
System.exit(1);
|
||||||
}
|
}
|
||||||
l.log("Server shut down.");
|
l.log("Server shut down.");
|
||||||
open=false;
|
open = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
I2PServerSocket i2pss = sockMgr.getServerSocket();
|
I2PServerSocket i2pss = sockMgr.getServerSocket();
|
||||||
|
@ -28,48 +28,85 @@ public abstract class I2PTunnelTask implements EventDispatcher {
|
|||||||
|
|
||||||
protected I2PTunnelTask(String name, EventDispatcher notifyThis) {
|
protected I2PTunnelTask(String name, EventDispatcher notifyThis) {
|
||||||
attachEventDispatcher(notifyThis);
|
attachEventDispatcher(notifyThis);
|
||||||
this.name=name;
|
this.name = name;
|
||||||
this.id = -1;
|
this.id = -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** for apps that use multiple I2PTunnel instances */
|
/** for apps that use multiple I2PTunnel instances */
|
||||||
public void setTunnel(I2PTunnel pTunnel) { tunnel = pTunnel; }
|
public void setTunnel(I2PTunnel pTunnel) {
|
||||||
|
tunnel = pTunnel;
|
||||||
|
}
|
||||||
|
|
||||||
public int getId() {
|
public int getId() {
|
||||||
return this.id;
|
return this.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isOpen() {return open;}
|
public boolean isOpen() {
|
||||||
|
return open;
|
||||||
|
}
|
||||||
|
|
||||||
public void setId(int id) {
|
public void setId(int id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void setName(String name) {
|
protected void setName(String name) {
|
||||||
this.name=name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void routerDisconnected() { tunnel.routerDisconnected(); }
|
protected void routerDisconnected() {
|
||||||
|
tunnel.routerDisconnected();
|
||||||
|
}
|
||||||
|
|
||||||
public abstract boolean close(boolean forced);
|
public abstract boolean close(boolean forced);
|
||||||
|
|
||||||
public void disconnected(I2PSession session) { routerDisconnected(); }
|
public void disconnected(I2PSession session) {
|
||||||
public void errorOccurred(I2PSession session, String message,
|
routerDisconnected();
|
||||||
Throwable error) {}
|
}
|
||||||
public void reportAbuse(I2PSession session, int severity) {}
|
|
||||||
|
public void errorOccurred(I2PSession session, String message, Throwable error) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public void reportAbuse(I2PSession session, int severity) {
|
||||||
|
}
|
||||||
|
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Required by the EventDispatcher interface */
|
/* Required by the EventDispatcher interface */
|
||||||
public EventDispatcher getEventDispatcher() { return _event; }
|
public EventDispatcher getEventDispatcher() {
|
||||||
public void attachEventDispatcher(EventDispatcher e) { _event.attachEventDispatcher(e.getEventDispatcher()); }
|
return _event;
|
||||||
public void detachEventDispatcher(EventDispatcher e) { _event.detachEventDispatcher(e.getEventDispatcher()); }
|
}
|
||||||
public void notifyEvent(String e, Object a) { _event.notifyEvent(e,a); }
|
|
||||||
public Object getEventValue(String n) { return _event.getEventValue(n); }
|
public void attachEventDispatcher(EventDispatcher e) {
|
||||||
public Set getEvents() { return _event.getEvents(); }
|
_event.attachEventDispatcher(e.getEventDispatcher());
|
||||||
public void ignoreEvents() { _event.ignoreEvents(); }
|
}
|
||||||
public void unIgnoreEvents() { _event.unIgnoreEvents(); }
|
|
||||||
public Object waitEventValue(String n) { return _event.waitEventValue(n); }
|
public void detachEventDispatcher(EventDispatcher e) {
|
||||||
|
_event.detachEventDispatcher(e.getEventDispatcher());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void notifyEvent(String e, Object a) {
|
||||||
|
_event.notifyEvent(e, a);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object getEventValue(String n) {
|
||||||
|
return _event.getEventValue(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set getEvents() {
|
||||||
|
return _event.getEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ignoreEvents() {
|
||||||
|
_event.ignoreEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unIgnoreEvents() {
|
||||||
|
_event.unIgnoreEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object waitEventValue(String n) {
|
||||||
|
return _event.waitEventValue(n);
|
||||||
|
}
|
||||||
}
|
}
|
@ -22,17 +22,17 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
|
|||||||
|
|
||||||
private static final int PING_COUNT = 3;
|
private static final int PING_COUNT = 3;
|
||||||
private static final int CPING_COUNT = 5;
|
private static final int CPING_COUNT = 5;
|
||||||
private static final int PING_TIMEOUT= 5000;
|
private static final int PING_TIMEOUT = 5000;
|
||||||
|
|
||||||
private static final long PING_DISTANCE=1000;
|
private static final long PING_DISTANCE = 1000;
|
||||||
|
|
||||||
private int MAX_SIMUL_PINGS=10; // not really final...
|
private int MAX_SIMUL_PINGS = 10; // not really final...
|
||||||
|
|
||||||
private boolean countPing=false;
|
private boolean countPing = false;
|
||||||
|
|
||||||
private I2PSocketManager sockMgr;
|
private I2PSocketManager sockMgr;
|
||||||
private Logging l;
|
private Logging l;
|
||||||
private boolean finished=false;
|
private boolean finished = false;
|
||||||
private String command;
|
private String command;
|
||||||
private long timeout = PING_TIMEOUT;
|
private long timeout = PING_TIMEOUT;
|
||||||
|
|
||||||
@ -47,12 +47,11 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
|
|||||||
// I2Ping(cmd, l, (EventDispatcher)null);
|
// I2Ping(cmd, l, (EventDispatcher)null);
|
||||||
//}
|
//}
|
||||||
|
|
||||||
public I2Ping(String cmd, Logging l,
|
public I2Ping(String cmd, Logging l, boolean ownDest, EventDispatcher notifyThis) {
|
||||||
boolean ownDest, EventDispatcher notifyThis) {
|
super("I2Ping [" + cmd + "]", notifyThis);
|
||||||
super("I2Ping ["+cmd+"]", notifyThis);
|
this.l = l;
|
||||||
this.l=l;
|
command = cmd;
|
||||||
command=cmd;
|
synchronized (slock) {
|
||||||
synchronized(slock) {
|
|
||||||
if (ownDest) {
|
if (ownDest) {
|
||||||
sockMgr = I2PTunnelClient.buildSocketManager();
|
sockMgr = I2PTunnelClient.buildSocketManager();
|
||||||
} else {
|
} else {
|
||||||
@ -62,7 +61,7 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
|
|||||||
Thread t = new I2PThread(this);
|
Thread t = new I2PThread(this);
|
||||||
t.setName("Client");
|
t.setName("Client");
|
||||||
t.start();
|
t.start();
|
||||||
open=true;
|
open = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
@ -71,19 +70,18 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
|
|||||||
runCommand(command);
|
runCommand(command);
|
||||||
} catch (InterruptedException ex) {
|
} catch (InterruptedException ex) {
|
||||||
l.log("*** Interrupted");
|
l.log("*** Interrupted");
|
||||||
_log.error("Pinger interrupted",ex);
|
_log.error("Pinger interrupted", ex);
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
_log.error("Pinger exception",ex);
|
_log.error("Pinger exception", ex);
|
||||||
}
|
}
|
||||||
l.log("*** Finished.");
|
l.log("*** Finished.");
|
||||||
synchronized(lock) {
|
synchronized (lock) {
|
||||||
finished=true;
|
finished = true;
|
||||||
}
|
}
|
||||||
close(false);
|
close(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void runCommand(String cmd) throws InterruptedException,
|
public void runCommand(String cmd) throws InterruptedException, IOException {
|
||||||
IOException {
|
|
||||||
if (cmd.startsWith("-t ")) { // timeout
|
if (cmd.startsWith("-t ")) { // timeout
|
||||||
cmd = cmd.substring(3);
|
cmd = cmd.substring(3);
|
||||||
int pos = cmd.indexOf(" ");
|
int pos = cmd.indexOf(" ");
|
||||||
@ -92,7 +90,7 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
|
|||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
timeout = Long.parseLong(cmd.substring(0, pos));
|
timeout = Long.parseLong(cmd.substring(0, pos));
|
||||||
cmd=cmd.substring(pos+1);
|
cmd = cmd.substring(pos + 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (cmd.startsWith("-m ")) { // max simultaneous pings
|
if (cmd.startsWith("-m ")) { // max simultaneous pings
|
||||||
@ -103,19 +101,18 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
|
|||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
MAX_SIMUL_PINGS = Integer.parseInt(cmd.substring(0, pos));
|
MAX_SIMUL_PINGS = Integer.parseInt(cmd.substring(0, pos));
|
||||||
cmd=cmd.substring(pos+1);
|
cmd = cmd.substring(pos + 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (cmd.startsWith("-c ")) { // "count" ping
|
if (cmd.startsWith("-c ")) { // "count" ping
|
||||||
countPing=true;
|
countPing = true;
|
||||||
cmd=cmd.substring(3);
|
cmd = cmd.substring(3);
|
||||||
}
|
}
|
||||||
if (cmd.equals("-h")) { // ping all hosts
|
if (cmd.equals("-h")) { // ping all hosts
|
||||||
cmd="-l hosts.txt";
|
cmd = "-l hosts.txt";
|
||||||
}
|
}
|
||||||
if (cmd.startsWith("-l ")) { // ping a list of hosts
|
if (cmd.startsWith("-l ")) { // ping a list of hosts
|
||||||
BufferedReader br = new BufferedReader
|
BufferedReader br = new BufferedReader(new FileReader(cmd.substring(3)));
|
||||||
(new FileReader(cmd.substring(3)));
|
|
||||||
String line;
|
String line;
|
||||||
List pingHandlers = new ArrayList();
|
List pingHandlers = new ArrayList();
|
||||||
while ((line = br.readLine()) != null) {
|
while ((line = br.readLine()) != null) {
|
||||||
@ -123,12 +120,12 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
|
|||||||
if (line.startsWith(";")) continue;
|
if (line.startsWith(";")) continue;
|
||||||
if (line.startsWith("!")) continue;
|
if (line.startsWith("!")) continue;
|
||||||
if (line.indexOf("=") != -1) { // maybe file is hosts.txt?
|
if (line.indexOf("=") != -1) { // maybe file is hosts.txt?
|
||||||
line=line.substring(0,line.indexOf("="));
|
line = line.substring(0, line.indexOf("="));
|
||||||
}
|
}
|
||||||
pingHandlers.add(new PingHandler(line));
|
pingHandlers.add(new PingHandler(line));
|
||||||
}
|
}
|
||||||
br.close();
|
br.close();
|
||||||
for (Iterator it= pingHandlers.iterator(); it.hasNext(); ) {
|
for (Iterator it = pingHandlers.iterator(); it.hasNext();) {
|
||||||
Thread t = (Thread) it.next();
|
Thread t = (Thread) it.next();
|
||||||
t.join();
|
t.join();
|
||||||
}
|
}
|
||||||
@ -141,34 +138,33 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
|
|||||||
|
|
||||||
public boolean close(boolean forced) {
|
public boolean close(boolean forced) {
|
||||||
if (!open) return true;
|
if (!open) return true;
|
||||||
synchronized(lock) {
|
synchronized (lock) {
|
||||||
if (!forced && !finished) {
|
if (!forced && !finished) {
|
||||||
l.log("There are still pings running!");
|
l.log("There are still pings running!");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
l.log("Closing pinger "+toString());
|
l.log("Closing pinger " + toString());
|
||||||
l.log("Pinger closed.");
|
l.log("Pinger closed.");
|
||||||
open=false;
|
open = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean ping(Destination dest) throws I2PException {
|
public boolean ping(Destination dest) throws I2PException {
|
||||||
try {
|
try {
|
||||||
synchronized(simulLock) {
|
synchronized (simulLock) {
|
||||||
while (simulPings >= MAX_SIMUL_PINGS) {
|
while (simulPings >= MAX_SIMUL_PINGS) {
|
||||||
simulLock.wait();
|
simulLock.wait();
|
||||||
}
|
}
|
||||||
simulPings++;
|
simulPings++;
|
||||||
while (lastPingTime + PING_DISTANCE >
|
while (lastPingTime + PING_DISTANCE > System.currentTimeMillis()) {
|
||||||
System.currentTimeMillis()) {
|
|
||||||
// no wait here, to delay all pingers
|
// no wait here, to delay all pingers
|
||||||
Thread.sleep(PING_DISTANCE/2);
|
Thread.sleep(PING_DISTANCE / 2);
|
||||||
}
|
}
|
||||||
lastPingTime=System.currentTimeMillis();
|
lastPingTime = System.currentTimeMillis();
|
||||||
}
|
}
|
||||||
boolean sent = sockMgr.ping(dest, PING_TIMEOUT);
|
boolean sent = sockMgr.ping(dest, PING_TIMEOUT);
|
||||||
synchronized(simulLock) {
|
synchronized (simulLock) {
|
||||||
simulPings--;
|
simulPings--;
|
||||||
simulLock.notifyAll();
|
simulLock.notifyAll();
|
||||||
}
|
}
|
||||||
@ -179,30 +175,27 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
public class PingHandler extends I2PThread {
|
public class PingHandler extends I2PThread {
|
||||||
private String destination;
|
private String destination;
|
||||||
|
|
||||||
public PingHandler(String dest) {
|
public PingHandler(String dest) {
|
||||||
this.destination=dest;
|
this.destination = dest;
|
||||||
setName("PingHandler for " + dest);
|
setName("PingHandler for " + dest);
|
||||||
start();
|
start();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
Destination dest=I2PTunnel.destFromName(destination);
|
Destination dest = I2PTunnel.destFromName(destination);
|
||||||
if (dest == null) {
|
if (dest == null) {
|
||||||
synchronized(lock) { // Logger is not thread safe
|
synchronized (lock) { // Logger is not thread safe
|
||||||
l.log("Unresolvable: "+destination+"");
|
l.log("Unresolvable: " + destination + "");
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int cnt = countPing ? CPING_COUNT : PING_COUNT;
|
int cnt = countPing ? CPING_COUNT : PING_COUNT;
|
||||||
StringBuffer pingResults = new StringBuffer
|
StringBuffer pingResults = new StringBuffer(2 * cnt + destination.length() + 3);
|
||||||
(2*cnt+ destination.length()+3);
|
for (int i = 0; i < cnt; i++) {
|
||||||
for (int i=0;i<cnt; i++) {
|
|
||||||
boolean sent;
|
boolean sent;
|
||||||
sent = ping(dest);
|
sent = ping(dest);
|
||||||
if (countPing) {
|
if (countPing) {
|
||||||
@ -213,12 +206,12 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
|
|||||||
pingResults.append("+ ");
|
pingResults.append("+ ");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
pingResults.append(sent?"+ ":"- ");
|
pingResults.append(sent ? "+ " : "- ");
|
||||||
}
|
}
|
||||||
// System.out.println(sent+" -> "+destination);
|
// System.out.println(sent+" -> "+destination);
|
||||||
}
|
}
|
||||||
pingResults.append(" ").append(destination);
|
pingResults.append(" ").append(destination);
|
||||||
synchronized(lock) { // Logger is not thread safe
|
synchronized (lock) { // Logger is not thread safe
|
||||||
l.log(pingResults.toString());
|
l.log(pingResults.toString());
|
||||||
}
|
}
|
||||||
} catch (I2PException ex) {
|
} catch (I2PException ex) {
|
||||||
|
@ -3,7 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
package net.i2p.i2ptunnel;
|
package net.i2p.i2ptunnel;
|
||||||
|
|
||||||
|
|
||||||
public interface Logging {
|
public interface Logging {
|
||||||
public void log(String s);
|
public void log(String s);
|
||||||
}
|
}
|
@ -155,6 +155,7 @@ public class TunnelManager implements Runnable {
|
|||||||
public TunnelManager(int listenPort) {
|
public TunnelManager(int listenPort) {
|
||||||
this(null, listenPort);
|
this(null, listenPort);
|
||||||
}
|
}
|
||||||
|
|
||||||
public TunnelManager(String listenHost, int listenPort) {
|
public TunnelManager(String listenHost, int listenPort) {
|
||||||
_tunnel = new I2PTunnel();
|
_tunnel = new I2PTunnel();
|
||||||
_keepAccepting = true;
|
_keepAccepting = true;
|
||||||
@ -218,9 +219,15 @@ public class TunnelManager implements Runnable {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
_log.error("Other error?!", e);
|
_log.error("Other error?!", e);
|
||||||
} finally {
|
} finally {
|
||||||
if (_socket != null) try { _socket.close(); } catch (IOException ioe) {}
|
if (_socket != null) try {
|
||||||
|
_socket.close();
|
||||||
|
} catch (IOException ioe) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Thread.sleep(5000);
|
||||||
|
} catch (InterruptedException ie) {
|
||||||
}
|
}
|
||||||
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void error(String msg, OutputStream out) throws IOException {
|
public void error(String msg, OutputStream out) throws IOException {
|
||||||
@ -240,7 +247,7 @@ public class TunnelManager implements Runnable {
|
|||||||
Object obj = _tunnel.waitEventValue("listDone");
|
Object obj = _tunnel.waitEventValue("listDone");
|
||||||
long endCommand = Clock.getInstance().now();
|
long endCommand = Clock.getInstance().now();
|
||||||
String str = buf.getBuffer();
|
String str = buf.getBuffer();
|
||||||
_log.debug("ListDone complete after " + (endCommand-startCommand) + "ms: [" + str + "]");
|
_log.debug("ListDone complete after " + (endCommand - startCommand) + "ms: [" + str + "]");
|
||||||
out.write(str.getBytes());
|
out.write(str.getBytes());
|
||||||
out.write('\n');
|
out.write('\n');
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
@ -249,7 +256,7 @@ public class TunnelManager implements Runnable {
|
|||||||
public void processListenOn(String ip, OutputStream out) throws IOException {
|
public void processListenOn(String ip, OutputStream out) throws IOException {
|
||||||
BufferLogger buf = new BufferLogger();
|
BufferLogger buf = new BufferLogger();
|
||||||
_tunnel.runCommand("listen_on " + ip, buf);
|
_tunnel.runCommand("listen_on " + ip, buf);
|
||||||
String status = (String)_tunnel.waitEventValue("listen_onResult");
|
String status = (String) _tunnel.waitEventValue("listen_onResult");
|
||||||
out.write((status + "\n").getBytes());
|
out.write((status + "\n").getBytes());
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
}
|
}
|
||||||
@ -262,7 +269,7 @@ public class TunnelManager implements Runnable {
|
|||||||
public void processLookup(String name, OutputStream out) throws IOException {
|
public void processLookup(String name, OutputStream out) throws IOException {
|
||||||
BufferLogger buf = new BufferLogger();
|
BufferLogger buf = new BufferLogger();
|
||||||
_tunnel.runCommand("lookup " + name, buf);
|
_tunnel.runCommand("lookup " + name, buf);
|
||||||
String rv = (String)_tunnel.waitEventValue("lookupResult");
|
String rv = (String) _tunnel.waitEventValue("lookupResult");
|
||||||
out.write(rv.getBytes());
|
out.write(rv.getBytes());
|
||||||
out.write('\n');
|
out.write('\n');
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
@ -294,8 +301,8 @@ public class TunnelManager implements Runnable {
|
|||||||
|
|
||||||
public void processClose(String which, boolean forced, OutputStream out) throws IOException {
|
public void processClose(String which, boolean forced, OutputStream out) throws IOException {
|
||||||
BufferLogger buf = new BufferLogger();
|
BufferLogger buf = new BufferLogger();
|
||||||
_tunnel.runCommand((forced?"close forced ":"close ") + which, buf);
|
_tunnel.runCommand((forced ? "close forced " : "close ") + which, buf);
|
||||||
String str = (String)_tunnel.waitEventValue("closeResult");
|
String str = (String) _tunnel.waitEventValue("closeResult");
|
||||||
out.write((str + "\n").getBytes());
|
out.write((str + "\n").getBytes());
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
}
|
}
|
||||||
@ -308,8 +315,8 @@ public class TunnelManager implements Runnable {
|
|||||||
public void processGenKey(OutputStream out) throws IOException {
|
public void processGenKey(OutputStream out) throws IOException {
|
||||||
BufferLogger buf = new BufferLogger();
|
BufferLogger buf = new BufferLogger();
|
||||||
_tunnel.runCommand("gentextkeys", buf);
|
_tunnel.runCommand("gentextkeys", buf);
|
||||||
String priv = (String)_tunnel.waitEventValue("privateKey");
|
String priv = (String) _tunnel.waitEventValue("privateKey");
|
||||||
String pub = (String)_tunnel.waitEventValue("publicDestination");
|
String pub = (String) _tunnel.waitEventValue("publicDestination");
|
||||||
out.write((pub + "\t" + priv).getBytes());
|
out.write((pub + "\t" + priv).getBytes());
|
||||||
out.write('\n');
|
out.write('\n');
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
@ -318,13 +325,13 @@ public class TunnelManager implements Runnable {
|
|||||||
public void processOpenClient(int listenPort, String peer, OutputStream out) throws IOException {
|
public void processOpenClient(int listenPort, String peer, OutputStream out) throws IOException {
|
||||||
BufferLogger buf = new BufferLogger();
|
BufferLogger buf = new BufferLogger();
|
||||||
_tunnel.runCommand("client " + listenPort + " " + peer, buf);
|
_tunnel.runCommand("client " + listenPort + " " + peer, buf);
|
||||||
Integer taskId = (Integer)_tunnel.waitEventValue("clientTaskId");
|
Integer taskId = (Integer) _tunnel.waitEventValue("clientTaskId");
|
||||||
if (taskId.intValue() < 0) {
|
if (taskId.intValue() < 0) {
|
||||||
out.write("error\n".getBytes());
|
out.write("error\n".getBytes());
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String rv = (String)_tunnel.waitEventValue("openClientResult");
|
String rv = (String) _tunnel.waitEventValue("openClientResult");
|
||||||
if (rv.equals("error")) {
|
if (rv.equals("error")) {
|
||||||
out.write((rv + "\n").getBytes());
|
out.write((rv + "\n").getBytes());
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
@ -336,24 +343,21 @@ public class TunnelManager implements Runnable {
|
|||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Integer port = (Integer)_tunnel.waitEventValue("clientLocalPort");
|
Integer port = (Integer) _tunnel.waitEventValue("clientLocalPort");
|
||||||
out.write((rv + " " + port.intValue() + " [" + taskId.intValue()
|
out.write((rv + " " + port.intValue() + " [" + taskId.intValue() + "]\n").getBytes());
|
||||||
+ "]\n").getBytes());
|
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void processOpenHTTPClient(int listenPort,
|
public void processOpenHTTPClient(int listenPort, String proxy, OutputStream out) throws IOException {
|
||||||
String proxy,
|
|
||||||
OutputStream out) throws IOException {
|
|
||||||
BufferLogger buf = new BufferLogger();
|
BufferLogger buf = new BufferLogger();
|
||||||
_tunnel.runCommand("httpclient " + listenPort + " " + proxy, buf);
|
_tunnel.runCommand("httpclient " + listenPort + " " + proxy, buf);
|
||||||
Integer taskId = (Integer)_tunnel.waitEventValue("httpclientTaskId");
|
Integer taskId = (Integer) _tunnel.waitEventValue("httpclientTaskId");
|
||||||
if (taskId.intValue() < 0) {
|
if (taskId.intValue() < 0) {
|
||||||
out.write("error\n".getBytes());
|
out.write("error\n".getBytes());
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String rv = (String)_tunnel.waitEventValue("openHTTPClientResult");
|
String rv = (String) _tunnel.waitEventValue("openHTTPClientResult");
|
||||||
if (rv.equals("error")) {
|
if (rv.equals("error")) {
|
||||||
out.write((rv + "\n").getBytes());
|
out.write((rv + "\n").getBytes());
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
@ -365,23 +369,21 @@ public class TunnelManager implements Runnable {
|
|||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Integer port = (Integer)_tunnel.waitEventValue("clientLocalPort");
|
Integer port = (Integer) _tunnel.waitEventValue("clientLocalPort");
|
||||||
out.write((rv + " " + port.intValue() + " [" + taskId.intValue()
|
out.write((rv + " " + port.intValue() + " [" + taskId.intValue() + "]\n").getBytes());
|
||||||
+ "]\n").getBytes());
|
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void processOpenSOCKSTunnel(int listenPort,
|
public void processOpenSOCKSTunnel(int listenPort, OutputStream out) throws IOException {
|
||||||
OutputStream out) throws IOException {
|
|
||||||
BufferLogger buf = new BufferLogger();
|
BufferLogger buf = new BufferLogger();
|
||||||
_tunnel.runCommand("sockstunnel " + listenPort, buf);
|
_tunnel.runCommand("sockstunnel " + listenPort, buf);
|
||||||
Integer taskId = (Integer)_tunnel.waitEventValue("sockstunnelTaskId");
|
Integer taskId = (Integer) _tunnel.waitEventValue("sockstunnelTaskId");
|
||||||
if (taskId.intValue() < 0) {
|
if (taskId.intValue() < 0) {
|
||||||
out.write("error\n".getBytes());
|
out.write("error\n".getBytes());
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String rv = (String)_tunnel.waitEventValue("openSOCKSTunnelResult");
|
String rv = (String) _tunnel.waitEventValue("openSOCKSTunnelResult");
|
||||||
if (rv.equals("error")) {
|
if (rv.equals("error")) {
|
||||||
out.write((rv + "\n").getBytes());
|
out.write((rv + "\n").getBytes());
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
@ -393,23 +395,23 @@ public class TunnelManager implements Runnable {
|
|||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Integer port = (Integer)_tunnel.waitEventValue("clientLocalPort");
|
Integer port = (Integer) _tunnel.waitEventValue("clientLocalPort");
|
||||||
out.write((rv + " " + port.intValue() + " [" + taskId.intValue()
|
out.write((rv + " " + port.intValue() + " [" + taskId.intValue() + "]\n").getBytes());
|
||||||
+ "]\n").getBytes());
|
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void processOpenServer(String serverHost, int serverPort, String privateKeys, OutputStream out) throws IOException {
|
public void processOpenServer(String serverHost, int serverPort, String privateKeys, OutputStream out)
|
||||||
|
throws IOException {
|
||||||
BufferLogger buf = new BufferLogger();
|
BufferLogger buf = new BufferLogger();
|
||||||
_tunnel.runCommand("textserver " + serverHost + " " + serverPort + " " + privateKeys, buf);
|
_tunnel.runCommand("textserver " + serverHost + " " + serverPort + " " + privateKeys, buf);
|
||||||
Integer taskId = (Integer)_tunnel.waitEventValue("serverTaskId");
|
Integer taskId = (Integer) _tunnel.waitEventValue("serverTaskId");
|
||||||
if (taskId.intValue() < 0) {
|
if (taskId.intValue() < 0) {
|
||||||
out.write("error\n".getBytes());
|
out.write("error\n".getBytes());
|
||||||
buf.ignoreFurtherActions();
|
buf.ignoreFurtherActions();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
String rv = (String)_tunnel.waitEventValue("openServerResult");
|
String rv = (String) _tunnel.waitEventValue("openServerResult");
|
||||||
|
|
||||||
if (rv.equals("error")) {
|
if (rv.equals("error")) {
|
||||||
out.write((rv + "\n").getBytes());
|
out.write((rv + "\n").getBytes());
|
||||||
|
@ -34,12 +34,14 @@ class TunnelManagerClientRunner implements Runnable {
|
|||||||
OutputStream out = _clientSocket.getOutputStream();
|
OutputStream out = _clientSocket.getOutputStream();
|
||||||
|
|
||||||
String cmd = reader.readLine();
|
String cmd = reader.readLine();
|
||||||
if (cmd != null)
|
if (cmd != null) processCommand(cmd, out);
|
||||||
processCommand(cmd, out);
|
|
||||||
} catch (IOException ioe) {
|
} catch (IOException ioe) {
|
||||||
_log.error("Error processing client commands", ioe);
|
_log.error("Error processing client commands", ioe);
|
||||||
} finally {
|
} finally {
|
||||||
if (_clientSocket != null) try { _clientSocket.close(); } catch (IOException ioe) {}
|
if (_clientSocket != null) try {
|
||||||
|
_clientSocket.close();
|
||||||
|
} catch (IOException ioe) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_log.debug("Client closed");
|
_log.debug("Client closed");
|
||||||
}
|
}
|
||||||
@ -121,7 +123,7 @@ class TunnelManagerClientRunner implements Runnable {
|
|||||||
int listenPort = 0;
|
int listenPort = 0;
|
||||||
String proxy = "squid.i2p";
|
String proxy = "squid.i2p";
|
||||||
if (!tok.hasMoreTokens()) {
|
if (!tok.hasMoreTokens()) {
|
||||||
_mgr.error("Usage: openhttpclient <listenPort> [<proxy>]",out);
|
_mgr.error("Usage: openhttpclient <listenPort> [<proxy>]", out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@ -135,14 +137,14 @@ class TunnelManagerClientRunner implements Runnable {
|
|||||||
proxy = tok.nextToken();
|
proxy = tok.nextToken();
|
||||||
}
|
}
|
||||||
if (tok.hasMoreTokens()) {
|
if (tok.hasMoreTokens()) {
|
||||||
_mgr.error("Usage: openclient <listenport> [<proxy>]",out);
|
_mgr.error("Usage: openclient <listenport> [<proxy>]", out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_mgr.processOpenHTTPClient(listenPort, proxy, out);
|
_mgr.processOpenHTTPClient(listenPort, proxy, out);
|
||||||
} else if ("opensockstunnel".equalsIgnoreCase(cmd)) {
|
} else if ("opensockstunnel".equalsIgnoreCase(cmd)) {
|
||||||
int listenPort = 0;
|
int listenPort = 0;
|
||||||
if (!tok.hasMoreTokens()) {
|
if (!tok.hasMoreTokens()) {
|
||||||
_mgr.error("Usage: opensockstunnel <listenPort>",out);
|
_mgr.error("Usage: opensockstunnel <listenPort>", out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@ -153,7 +155,7 @@ class TunnelManagerClientRunner implements Runnable {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (tok.hasMoreTokens()) {
|
if (tok.hasMoreTokens()) {
|
||||||
_mgr.error("Usage: opensockstunnel <listenport>",out);
|
_mgr.error("Usage: opensockstunnel <listenport>", out);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_mgr.processOpenSOCKSTunnel(listenPort, out);
|
_mgr.processOpenSOCKSTunnel(listenPort, out);
|
||||||
|
@ -26,8 +26,7 @@ public class I2PSOCKSTunnel extends I2PTunnelClientBase {
|
|||||||
// I2PSOCKSTunnel(localPort, l, ownDest, (EventDispatcher)null);
|
// I2PSOCKSTunnel(localPort, l, ownDest, (EventDispatcher)null);
|
||||||
//}
|
//}
|
||||||
|
|
||||||
public I2PSOCKSTunnel(int localPort, Logging l, boolean ownDest,
|
public I2PSOCKSTunnel(int localPort, Logging l, boolean ownDest, EventDispatcher notifyThis) {
|
||||||
EventDispatcher notifyThis) {
|
|
||||||
super(localPort, ownDest, l, notifyThis, "SOCKSHandler");
|
super(localPort, ownDest, l, notifyThis, "SOCKSHandler");
|
||||||
|
|
||||||
if (waitEventValue("openBaseClientResult").equals("error")) {
|
if (waitEventValue("openBaseClientResult").equals("error")) {
|
||||||
@ -47,7 +46,7 @@ public class I2PSOCKSTunnel extends I2PTunnelClientBase {
|
|||||||
SOCKSServer serv = SOCKSServerFactory.createSOCKSServer(s);
|
SOCKSServer serv = SOCKSServerFactory.createSOCKSServer(s);
|
||||||
Socket clientSock = serv.getClientSocket();
|
Socket clientSock = serv.getClientSocket();
|
||||||
I2PSocket destSock = serv.getDestinationI2PSocket();
|
I2PSocket destSock = serv.getDestinationI2PSocket();
|
||||||
new I2PTunnelRunner (clientSock, destSock, sockLock, null);
|
new I2PTunnelRunner(clientSock, destSock, sockLock, null);
|
||||||
} catch (SOCKSException e) {
|
} catch (SOCKSException e) {
|
||||||
_log.error("Error from SOCKS connection: " + e.getMessage());
|
_log.error("Error from SOCKS connection: " + e.getMessage());
|
||||||
closeSocket(s);
|
closeSocket(s);
|
||||||
|
@ -52,9 +52,7 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected void setupServer() throws SOCKSException {
|
protected void setupServer() throws SOCKSException {
|
||||||
if (setupCompleted) {
|
if (setupCompleted) { return; }
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
DataInputStream in;
|
DataInputStream in;
|
||||||
DataOutputStream out;
|
DataOutputStream out;
|
||||||
@ -65,8 +63,7 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
init(in, out);
|
init(in, out);
|
||||||
manageRequest(in, out);
|
manageRequest(in, out);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new SOCKSException("Connection error ("
|
throw new SOCKSException("Connection error (" + e.getMessage() + ")");
|
||||||
+ e.getMessage() + ")");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setupCompleted = true;
|
setupCompleted = true;
|
||||||
@ -76,8 +73,7 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
* SOCKS5 connection initialization. This method assumes that
|
* SOCKS5 connection initialization. This method assumes that
|
||||||
* SOCKS "VER" field has been stripped from the input stream.
|
* SOCKS "VER" field has been stripped from the input stream.
|
||||||
*/
|
*/
|
||||||
private void init (DataInputStream in,
|
private void init(DataInputStream in, DataOutputStream out) throws IOException, SOCKSException {
|
||||||
DataOutputStream out) throws IOException, SOCKSException {
|
|
||||||
int nMethods = in.readByte() & 0xff;
|
int nMethods = in.readByte() & 0xff;
|
||||||
boolean methodOk = false;
|
boolean methodOk = false;
|
||||||
int method = Method.NO_ACCEPTABLE_METHODS;
|
int method = Method.NO_ACCEPTABLE_METHODS;
|
||||||
@ -97,8 +93,7 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
sendInitReply(Method.NO_AUTH_REQUIRED, out);
|
sendInitReply(Method.NO_AUTH_REQUIRED, out);
|
||||||
return;
|
return;
|
||||||
default:
|
default:
|
||||||
_log.debug("no suitable authentication methods found ("
|
_log.debug("no suitable authentication methods found (" + Integer.toHexString(method) + ")");
|
||||||
+ Integer.toHexString(method)+ ")");
|
|
||||||
sendInitReply(Method.NO_ACCEPTABLE_METHODS, out);
|
sendInitReply(Method.NO_ACCEPTABLE_METHODS, out);
|
||||||
throw new SOCKSException("Unsupported authentication method");
|
throw new SOCKSException("Unsupported authentication method");
|
||||||
}
|
}
|
||||||
@ -110,8 +105,7 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
* initialization, integrity/confidentiality encapsulations, etc)
|
* initialization, integrity/confidentiality encapsulations, etc)
|
||||||
* has been stripped out of the input/output streams.
|
* has been stripped out of the input/output streams.
|
||||||
*/
|
*/
|
||||||
private void manageRequest(DataInputStream in,
|
private void manageRequest(DataInputStream in, DataOutputStream out) throws IOException, SOCKSException {
|
||||||
DataOutputStream out) throws IOException, SOCKSException {
|
|
||||||
int socksVer = in.readByte() & 0xff;
|
int socksVer = in.readByte() & 0xff;
|
||||||
if (socksVer != SOCKS_VERSION_5) {
|
if (socksVer != SOCKS_VERSION_5) {
|
||||||
_log.debug("error in SOCKS5 request (protocol != 5? wtf?)");
|
_log.debug("error in SOCKS5 request (protocol != 5? wtf?)");
|
||||||
@ -124,19 +118,14 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
break;
|
break;
|
||||||
case Command.BIND:
|
case Command.BIND:
|
||||||
_log.debug("BIND command is not supported!");
|
_log.debug("BIND command is not supported!");
|
||||||
sendRequestReply(Reply.COMMAND_NOT_SUPPORTED,
|
sendRequestReply(Reply.COMMAND_NOT_SUPPORTED, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
|
||||||
AddressType.DOMAINNAME, null,
|
|
||||||
"0.0.0.0", 0, out);
|
|
||||||
throw new SOCKSException("BIND command not supported");
|
throw new SOCKSException("BIND command not supported");
|
||||||
case Command.UDP_ASSOCIATE:
|
case Command.UDP_ASSOCIATE:
|
||||||
_log.debug("UDP ASSOCIATE command is not supported!");
|
_log.debug("UDP ASSOCIATE command is not supported!");
|
||||||
sendRequestReply(Reply.COMMAND_NOT_SUPPORTED,
|
sendRequestReply(Reply.COMMAND_NOT_SUPPORTED, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
|
||||||
AddressType.DOMAINNAME, null,
|
|
||||||
"0.0.0.0", 0, out);
|
|
||||||
throw new SOCKSException("UDP ASSOCIATE command not supported");
|
throw new SOCKSException("UDP ASSOCIATE command not supported");
|
||||||
default:
|
default:
|
||||||
_log.debug("unknown command in request ("
|
_log.debug("unknown command in request (" + Integer.toHexString(command) + ")");
|
||||||
+ Integer.toHexString(command) + ")");
|
|
||||||
throw new SOCKSException("Invalid command in request");
|
throw new SOCKSException("Invalid command in request");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -156,8 +145,7 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
connHostName += ".";
|
connHostName += ".";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_log.warn("IPV4 address type in request: " + connHostName
|
_log.warn("IPV4 address type in request: " + connHostName + ". Is your client secure?");
|
||||||
+ ". Is your client secure?");
|
|
||||||
break;
|
break;
|
||||||
case AddressType.DOMAINNAME:
|
case AddressType.DOMAINNAME:
|
||||||
{
|
{
|
||||||
@ -173,15 +161,11 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
_log.debug("DOMAINNAME address type in request: " + connHostName);
|
_log.debug("DOMAINNAME address type in request: " + connHostName);
|
||||||
break;
|
break;
|
||||||
case AddressType.IPV6:
|
case AddressType.IPV6:
|
||||||
_log.warn("IP V6 address type in request! Is your client secure?"
|
_log.warn("IP V6 address type in request! Is your client secure?" + " (IPv6 is not supported, anyway :-)");
|
||||||
+ " (IPv6 is not supported, anyway :-)");
|
sendRequestReply(Reply.ADDRESS_TYPE_NOT_SUPPORTED, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
|
||||||
sendRequestReply(Reply.ADDRESS_TYPE_NOT_SUPPORTED,
|
|
||||||
AddressType.DOMAINNAME, null,
|
|
||||||
"0.0.0.0", 0, out);
|
|
||||||
throw new SOCKSException("IPV6 addresses not supported");
|
throw new SOCKSException("IPV6 addresses not supported");
|
||||||
default:
|
default:
|
||||||
_log.debug("unknown address type in request ("
|
_log.debug("unknown address type in request (" + Integer.toHexString(command) + ")");
|
||||||
+ Integer.toHexString(command) + ")");
|
|
||||||
throw new SOCKSException("Invalid addresses type in request");
|
throw new SOCKSException("Invalid addresses type in request");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -198,21 +182,16 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
try {
|
try {
|
||||||
out = new DataOutputStream(clientSock.getOutputStream());
|
out = new DataOutputStream(clientSock.getOutputStream());
|
||||||
|
|
||||||
sendRequestReply(Reply.SUCCEEDED,
|
sendRequestReply(Reply.SUCCEEDED, AddressType.IPV4, InetAddress.getByName("127.0.0.1"), null, 1, out);
|
||||||
AddressType.IPV4,
|
|
||||||
InetAddress.getByName("127.0.0.1"),
|
|
||||||
null, 1, out);
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new SOCKSException("Connection error ("
|
throw new SOCKSException("Connection error (" + e.getMessage() + ")");
|
||||||
+ e.getMessage() + ")");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send the specified reply during SOCKS5 initialization
|
* Send the specified reply during SOCKS5 initialization
|
||||||
*/
|
*/
|
||||||
private void sendInitReply(int replyCode,
|
private void sendInitReply(int replyCode, DataOutputStream out) throws IOException {
|
||||||
DataOutputStream out) throws IOException {
|
|
||||||
ByteArrayOutputStream reps = new ByteArrayOutputStream();
|
ByteArrayOutputStream reps = new ByteArrayOutputStream();
|
||||||
|
|
||||||
reps.write(SOCKS_VERSION_5);
|
reps.write(SOCKS_VERSION_5);
|
||||||
@ -232,12 +211,8 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
* one of inetAddr or domainName can be null, depending on
|
* one of inetAddr or domainName can be null, depending on
|
||||||
* addressType.
|
* addressType.
|
||||||
*/
|
*/
|
||||||
private void sendRequestReply(int replyCode,
|
private void sendRequestReply(int replyCode, int addressType, InetAddress inetAddr, String domainName,
|
||||||
int addressType,
|
int bindPort, DataOutputStream out) throws IOException {
|
||||||
InetAddress inetAddr,
|
|
||||||
String domainName,
|
|
||||||
int bindPort,
|
|
||||||
DataOutputStream out) throws IOException {
|
|
||||||
ByteArrayOutputStream reps = new ByteArrayOutputStream();
|
ByteArrayOutputStream reps = new ByteArrayOutputStream();
|
||||||
DataOutputStream dreps = new DataOutputStream(reps);
|
DataOutputStream dreps = new DataOutputStream(reps);
|
||||||
|
|
||||||
@ -258,8 +233,7 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
dreps.writeBytes(domainName);
|
dreps.writeBytes(domainName);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
_log.error("unknown address type passed to sendReply() ("
|
_log.error("unknown address type passed to sendReply() (" + Integer.toHexString(addressType) + ")! wtf?");
|
||||||
+ Integer.toHexString(addressType) + ")! wtf?");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -274,7 +248,6 @@ public class SOCKS5Server extends SOCKSServer {
|
|||||||
out.write(reply);
|
out.write(reply);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Some namespaces to enclose SOCKS protocol codes
|
* Some namespaces to enclose SOCKS protocol codes
|
||||||
*/
|
*/
|
||||||
|
@ -47,7 +47,6 @@ public abstract class SOCKSServer {
|
|||||||
*/
|
*/
|
||||||
public abstract Socket getClientSocket() throws SOCKSException;
|
public abstract Socket getClientSocket() throws SOCKSException;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Confirm to the client that the connection has succeeded
|
* Confirm to the client that the connection has succeeded
|
||||||
*/
|
*/
|
||||||
@ -80,8 +79,7 @@ public abstract class SOCKSServer {
|
|||||||
if (connHostName.toLowerCase().endsWith(".i2p")) {
|
if (connHostName.toLowerCase().endsWith(".i2p")) {
|
||||||
_log.debug("connecting to " + connHostName + "...");
|
_log.debug("connecting to " + connHostName + "...");
|
||||||
I2PSocketManager sm = I2PSocketManagerFactory.createManager();
|
I2PSocketManager sm = I2PSocketManagerFactory.createManager();
|
||||||
destSock = sm.connect(I2PTunnel.destFromName(connHostName),
|
destSock = sm.connect(I2PTunnel.destFromName(connHostName), new I2PSocketOptions());
|
||||||
new I2PSocketOptions());
|
|
||||||
confirmConnection();
|
confirmConnection();
|
||||||
_log.debug("connection confirmed - exchanging data...");
|
_log.debug("connection confirmed - exchanging data...");
|
||||||
} else {
|
} else {
|
||||||
|
@ -34,18 +34,17 @@ public class SOCKSServerFactory {
|
|||||||
int socksVer = in.readByte();
|
int socksVer = in.readByte();
|
||||||
|
|
||||||
switch (socksVer) {
|
switch (socksVer) {
|
||||||
case 0x05: // SOCKS version 5
|
case 0x05:
|
||||||
|
// SOCKS version 5
|
||||||
serv = new SOCKS5Server(s);
|
serv = new SOCKS5Server(s);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
_log.debug("SOCKS protocol version not supported ("
|
_log.debug("SOCKS protocol version not supported (" + Integer.toHexString(socksVer) + ")");
|
||||||
+ Integer.toHexString(socksVer) + ")");
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
_log.debug("error reading SOCKS protocol version");
|
_log.debug("error reading SOCKS protocol version");
|
||||||
throw new SOCKSException("Connection error ("
|
throw new SOCKSException("Connection error (" + e.getMessage() + ")");
|
||||||
+ e.getMessage() + ")");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return serv;
|
return serv;
|
||||||
|
Reference in New Issue
Block a user