beginning of format, updated imports. (shendaras)

This commit is contained in:
shendaras
2004-04-10 11:45:02 +00:00
committed by zzz
parent 8a8e68146f
commit 17a1b11f66
37 changed files with 3546 additions and 3511 deletions

View File

@ -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
@ -106,17 +112,18 @@ class ClientEngine {
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) {
}
}
}
}

View File

@ -83,7 +83,9 @@ 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() {
@ -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();
@ -167,6 +170,7 @@ public class Heartbeat {
engine.startEngine();
}
}
/** stop all of the tests */
public void stopEngines() {
for (Iterator iter = _clientEngines.values().iterator(); iter.hasNext();) {
@ -204,7 +208,8 @@ public class Heartbeat {
synchronized (o) {
o.wait();
}
} catch (InterruptedException ie) {}
} catch (InterruptedException ie) {
}
}
}

View File

@ -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
@ -201,7 +210,8 @@ class I2PAdapter {
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) {
@ -289,25 +301,27 @@ class I2PAdapter {
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;
@ -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();
}
}

View File

@ -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()));
}
/**
@ -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.
@ -139,15 +163,13 @@ public class PeerData {
*/
public double getLostMessages(int period) {
Rate rate = _lostRate.getRate(period * 60 * 1000);
if (rate == null)
return -1;
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;
if (rate == null) return -1;
return rate.getAverageValue();
}
@ -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;
}
}
}

View File

@ -42,10 +42,14 @@ class PeerDataWriter {
}
} 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;
}

View File

@ -16,6 +16,7 @@ class PeerPlotConfig {
}
// baf
}
// moo
private final static void biff() {

View File

@ -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,9 +39,7 @@ 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) {
Socket s = ss.accept();
@ -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();
}
}

View File

@ -33,7 +33,6 @@ public class HTTPSocketHandler extends Thread {
start();
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/

View File

@ -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");
}
@ -83,11 +80,13 @@ public class HTTPTunnel {
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;
@ -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)");
}
}

View File

@ -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;
@ -115,9 +114,7 @@ public class Request {
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) {

View File

@ -29,13 +29,9 @@ 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");
}
if (maxManagers < 1) { throw new IllegalArgumentException("maxManagers < 1"); }
this.host = host;
this.port = port;
this.shouldThrowAwayManagers = shouldThrowAwayManagers;
@ -48,7 +44,6 @@ public class SocketManagerProducer extends Thread {
start();
}
/**
* Thread producing new SocketManagers.
*/
@ -64,9 +59,7 @@ 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) {

View File

@ -16,7 +16,6 @@ public class ChainFilter implements Filter {
private Collection filters; // perhaps protected?
/**
* @param filters A collection (list) of filters to chain to
*/

View File

@ -1,4 +1,5 @@
package net.i2p.httptunnel.handler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
@ -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,8 +65,7 @@ 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;

View File

@ -1,4 +1,5 @@
package net.i2p.httptunnel.handler;
import java.io.IOException;
import java.io.OutputStream;
@ -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();
}
}

View File

@ -1,4 +1,5 @@
package net.i2p.httptunnel.handler;
import java.io.IOException;
import java.io.OutputStream;
@ -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");

View File

@ -1,4 +1,5 @@
package net.i2p.httptunnel.handler;
import java.io.IOException;
import java.io.OutputStream;
@ -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

View File

@ -1,4 +1,5 @@
package net.i2p.httptunnel.handler;
import java.io.IOException;
import java.io.OutputStream;
@ -45,8 +46,7 @@ public class RootHandler {
* @param out where to write the results
* @throws IOException
*/
public void handle(Request req, HTTPListener httpl,
OutputStream out) throws IOException {
public void handle(Request req, HTTPListener httpl, OutputStream out) throws IOException {
String url = req.getURL();
System.out.println(url);
/* boolean byProxy = false; */
@ -71,9 +71,9 @@ public class RootHandler {
// 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
@ -85,8 +85,7 @@ public class RootHandler {
if (url.equals("/")) { // main page
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;
@ -110,8 +109,7 @@ public class RootHandler {
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);

View File

@ -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());
}
/**

View File

@ -62,7 +62,6 @@ 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();
@ -71,10 +70,8 @@ public class I2PTunnel implements Logging, EventDispatcher {
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"};
@ -95,10 +92,11 @@ 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 checkRunByE = true;
boolean cli = true;
boolean dontDie = true;
for (int i = 0; i < args.length; i++) {
@ -109,8 +107,8 @@ public class I2PTunnel implements Logging, EventDispatcher {
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.");
_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;
@ -137,8 +135,7 @@ 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));
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("I2PTunnel>");
String cmd = r.readLine();
@ -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,6 +177,7 @@ 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(" ");
@ -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));
}
}
@ -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));
}
}
@ -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 {
@ -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");
}
}
@ -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 {
@ -635,9 +624,9 @@ 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
@ -688,8 +677,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
public void runRun(String args[], Logging l) {
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);
@ -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");
}
}
@ -759,8 +747,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
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));
}
}
@ -778,8 +765,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
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;
@ -814,9 +800,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
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,12 +824,10 @@ 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.");
@ -867,8 +849,7 @@ 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();
@ -890,8 +871,7 @@ 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 {
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,11 +884,9 @@ 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();
@ -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) {
@ -972,8 +952,7 @@ public class I2PTunnel implements Logging, EventDispatcher {
synchronized (listeners) {
for (Iterator iter = listeners.iterator(); iter.hasNext();) {
ConnectionEventListener lsnr = (ConnectionEventListener) iter.next();
if (lsnr != null)
lsnr.routerDisconnected();
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);
}
}

View File

@ -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")) {

View File

@ -23,8 +23,7 @@ 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;
@ -56,9 +55,7 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
// I2PTunnelClientBase(localPort, ownDest, l, (EventDispatcher)null);
//}
public I2PTunnelClientBase(int localPort, boolean ownDest,
Logging l, EventDispatcher notifyThis,
String handlerName) {
public I2PTunnelClientBase(int localPort, boolean ownDest, Logging l, EventDispatcher notifyThis, String handlerName) {
super(localPort + " (uninitialized)", notifyThis);
this.localPort = localPort;
this.l = l;
@ -83,8 +80,7 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
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,8 +190,7 @@ 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) {
@ -210,7 +203,8 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
while (!startRunning) {
try {
startLock.wait();
} catch (InterruptedException ie) {}
} catch (InterruptedException ie) {
}
}
}
@ -233,7 +227,6 @@ 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

View File

@ -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,9 +62,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
InactivityTimeoutThread timeoutThread = null;
try {
out = s.getOutputStream();
BufferedReader br = new BufferedReader
(new InputStreamReader(s.getInputStream(),
"ISO-8859-1"));
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) {
@ -75,8 +71,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
if (pos == -1) break;
method = line.substring(0, pos);
String request = line.substring(pos + 1);
if (request.startsWith("/") &&
System.getProperty("i2ptunnel.noproxy") != null) {
if (request.startsWith("/") && System.getProperty("i2ptunnel.noproxy") != null) {
request = "http://i2p" + request;
}
pos = request.indexOf("//");
@ -112,17 +107,14 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
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 + ")");
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 + ")");
if (_log.shouldLog(Log.INFO)) _log.info("host=getHostName(" + destination + ")");
host = getHostName(destination); // hide original host
}
@ -135,8 +127,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
} else if (line.startsWith("Host: ") && !usingWWWProxy) {
line = "Host: " + host;
if (_log.shouldLog(Log.INFO))
_log.info("Setting 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;
@ -162,8 +153,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
Destination dest = I2PTunnel.destFromName(destination);
if (dest == null) {
l.log("Could not resolve " + destination + ".");
writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest,
usingWWWProxy, destination);
writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest, usingWWWProxy, destination);
s.close();
return;
}
@ -176,15 +166,13 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
} 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);
}
}
@ -201,7 +189,8 @@ 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) {
public InactivityTimeoutThread(I2PTunnelRunner runner, OutputStream out, String targetRequest,
boolean useWWWProxy, Socket s) {
this.s = s;
_runner = runner;
_out = out;
@ -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);
@ -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,26 +281,20 @@ 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;
@ -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://");

View File

@ -42,8 +42,7 @@ public class I2PTunnelRunner extends I2PThread {
/** when the runner started up */
private long startedOn;
public I2PTunnelRunner(Socket s, I2PSocket i2ps, Object slock,
byte[] initialData) {
public I2PTunnelRunner(Socket s, I2PSocket i2ps, Object slock, byte[] initialData) {
this.s = s;
this.i2ps = i2ps;
this.slock = slock;
@ -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,24 +69,29 @@ 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) {
i2pout.write(initialData);
@ -141,8 +147,7 @@ public class I2PTunnelRunner extends I2PThread {
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
if (len > 0)
updateActivity();
if (len > 0) updateActivity();
if (in.available() == 0) {
try {

View File

@ -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,17 +40,14 @@ public class I2PTunnelServer extends I2PTunnelTask
private Logging l;
public I2PTunnelServer(InetAddress host, int port,
String privData, Logging l,
EventDispatcher 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) {
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);
@ -60,15 +56,14 @@ public class I2PTunnelServer extends I2PTunnelTask
notifyEvent("openServerResult", "error");
}
}
public I2PTunnelServer(InetAddress host, int port,
InputStream privData, String privkeyname,
Logging l, EventDispatcher 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) {
private void init(InetAddress host, int port, InputStream privData, String privkeyname, Logging l) {
this.l = l;
this.remoteHost = host;
this.remotePort = port;
@ -76,9 +71,8 @@ public class I2PTunnelServer extends I2PTunnelTask
Properties props = new Properties();
props.putAll(System.getProperties());
synchronized (slock) {
sockMgr = I2PSocketManagerFactory.createManager
(privData, I2PTunnel.host,
Integer.parseInt(I2PTunnel.port), props);
sockMgr = I2PSocketManagerFactory.createManager(privData, I2PTunnel.host, Integer.parseInt(I2PTunnel.port),
props);
}
l.log("Ready!");
@ -89,14 +83,12 @@ public class I2PTunnelServer extends I2PTunnelTask
t.start();
}
public boolean close(boolean forced) {
if (!open) return true;
synchronized (lock) {
if (!forced && sockMgr.listSockets().size() != 0) {
l.log("There are still active connections!");
for (Iterator it = sockMgr.listSockets().iterator();
it.hasNext();) {
for (Iterator it = sockMgr.listSockets().iterator(); it.hasNext();) {
l.log("->" + it.next());
}
return false;
@ -115,7 +107,6 @@ public class I2PTunnelServer extends I2PTunnelTask
}
}
public void run() {
try {
I2PServerSocket i2pss = sockMgr.getServerSocket();

View File

@ -33,13 +33,17 @@ public abstract class I2PTunnelTask implements EventDispatcher {
}
/** 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;
@ -49,27 +53,60 @@ public abstract class I2PTunnelTask implements EventDispatcher {
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);
}
}

View File

@ -47,8 +47,7 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
// I2Ping(cmd, l, (EventDispatcher)null);
//}
public I2Ping(String cmd, Logging l,
boolean ownDest, EventDispatcher notifyThis) {
public I2Ping(String cmd, Logging l, boolean ownDest, EventDispatcher notifyThis) {
super("I2Ping [" + cmd + "]", notifyThis);
this.l = l;
command = cmd;
@ -82,8 +81,7 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
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(" ");
@ -114,8 +112,7 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
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) {
@ -160,8 +157,7 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
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);
}
@ -179,8 +175,6 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
}
}
public class PingHandler extends I2PThread {
private String destination;
@ -200,8 +194,7 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
return;
}
int cnt = countPing ? CPING_COUNT : PING_COUNT;
StringBuffer pingResults = new StringBuffer
(2*cnt+ destination.length()+3);
StringBuffer pingResults = new StringBuffer(2 * cnt + destination.length() + 3);
for (int i = 0; i < cnt; i++) {
boolean sent;
sent = ping(dest);

View File

@ -3,7 +3,6 @@
*/
package net.i2p.i2ptunnel;
public interface Logging {
public void log(String s);
}

View File

@ -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 {
@ -337,14 +344,11 @@ public class TunnelManager implements Runnable {
return;
}
Integer port = (Integer) _tunnel.waitEventValue("clientLocalPort");
out.write((rv + " " + port.intValue() + " [" + taskId.intValue()
+ "]\n").getBytes());
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");
@ -366,13 +370,11 @@ public class TunnelManager implements Runnable {
return;
}
Integer port = (Integer) _tunnel.waitEventValue("clientLocalPort");
out.write((rv + " " + port.intValue() + " [" + taskId.intValue()
+ "]\n").getBytes());
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");
@ -394,12 +396,12 @@ public class TunnelManager implements Runnable {
return;
}
Integer port = (Integer) _tunnel.waitEventValue("clientLocalPort");
out.write((rv + " " + port.intValue() + " [" + taskId.intValue()
+ "]\n").getBytes());
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");

View File

@ -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");
}

View File

@ -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")) {

View File

@ -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
*/

View File

@ -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 {

View File

@ -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;