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