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

@ -16,16 +16,19 @@ class BufferLogger implements Logging {
private final static Log _log = new Log(BufferLogger.class);
private ByteArrayOutputStream _baos;
private boolean _ignore;
public BufferLogger() {
_baos = new ByteArrayOutputStream(512);
_ignore = false;
_baos = new ByteArrayOutputStream(512);
_ignore = false;
}
private final static String EMPTY = "";
public String getBuffer() {
if (_ignore) return EMPTY;
else return new String(_baos.toByteArray());
public String getBuffer() {
if (_ignore)
return EMPTY;
else
return new String(_baos.toByteArray());
}
/**
@ -36,27 +39,27 @@ class BufferLogger implements Logging {
*
*/
public void ignoreFurtherActions() {
_ignore = true;
synchronized (_baos) {
_baos.reset();
}
_baos = null;
_ignore = true;
synchronized (_baos) {
_baos.reset();
}
_baos = null;
}
/**
* Pass in some random data
* @param s String containing what we're logging.
*/
public void log(String s) {
if (_ignore) return;
if (s != null) {
_log.debug("logging [" + s + "]");
try {
_baos.write(s.getBytes());
_baos.write('\n');
} catch (IOException ioe) {
_log.error("Error logging [" + s + "]");
}
}
if (_ignore) return;
if (s != null) {
_log.debug("logging [" + s + "]");
try {
_baos.write(s.getBytes());
_baos.write('\n');
} catch (IOException ioe) {
_log.error("Error logging [" + s + "]");
}
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -18,44 +18,42 @@ public class I2PTunnelClient extends I2PTunnelClientBase {
protected Destination dest;
public I2PTunnelClient(int localPort, String destination,
Logging l, boolean ownDest,
EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "SynSender");
public I2PTunnelClient(int localPort, String destination, Logging l, boolean ownDest, EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "SynSender");
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openClientResult", "error");
return;
}
try {
dest=I2PTunnel.destFromName(destination);
if (dest == null) {
l.log("Could not resolve " + destination + ".");
return;
}
} catch (DataFormatException e) {
l.log("Bad format in destination \"" + destination + "\".");
notifyEvent("openClientResult", "error");
return;
}
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openClientResult", "error");
return;
}
setName(getLocalPort() + " -> " + destination);
try {
dest = I2PTunnel.destFromName(destination);
if (dest == null) {
l.log("Could not resolve " + destination + ".");
return;
}
} catch (DataFormatException e) {
l.log("Bad format in destination \"" + destination + "\".");
notifyEvent("openClientResult", "error");
return;
}
startRunning();
setName(getLocalPort() + " -> " + destination);
notifyEvent("openClientResult", "ok");
startRunning();
notifyEvent("openClientResult", "ok");
}
protected void clientConnectionRun(Socket s) {
try {
I2PSocket i2ps = createI2PSocket(dest);
new I2PTunnelRunner(s, i2ps, sockLock, null);
} catch (I2PException ex) {
_log.info("Error connecting", ex);
l.log("Unable to reach peer");
// s has been initialized before the try block...
closeSocket(s);
}
try {
I2PSocket i2ps = createI2PSocket(dest);
new I2PTunnelRunner(s, i2ps, sockLock, null);
} catch (I2PException ex) {
_log.info("Error connecting", ex);
l.log("Unable to reach peer");
// s has been initialized before the try block...
closeSocket(s);
}
}
}
}

View File

@ -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;
@ -41,12 +40,12 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
private boolean listenerReady = false;
private ServerSocket ss;
private Object startLock = new Object();
private boolean startRunning = false;
private Object closeLock = new Object();
private byte[] pubkey;
private String handlerName;
@ -56,101 +55,96 @@ 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;
this.l = l;
this.handlerName=handlerName;
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;
synchronized(sockLock) {
if (ownDest) {
sockMgr=buildSocketManager();
} else {
sockMgr=getSocketManager();
}
}
if (sockMgr == null) throw new NullPointerException();
l.log("I2P session created");
Thread t = new I2PThread(this);
t.setName("Client");
listenerReady=false;
t.start();
open=true;
synchronized (this) {
while (!listenerReady) {
try {
wait();
}
catch (InterruptedException e) {
// ignore
}
}
}
if (open && listenerReady) {
l.log("Ready! Port " + getLocalPort());
notifyEvent("openBaseClientResult", "ok");
} else {
l.log("Error!");
notifyEvent("openBaseClientResult", "error");
}
synchronized (sockLock) {
if (ownDest) {
sockMgr = buildSocketManager();
} else {
sockMgr = getSocketManager();
}
}
if (sockMgr == null) throw new NullPointerException();
l.log("I2P session created");
Thread t = new I2PThread(this);
t.setName("Client");
listenerReady = false;
t.start();
open = true;
synchronized (this) {
while (!listenerReady) {
try {
wait();
} catch (InterruptedException e) {
// ignore
}
}
}
if (open && listenerReady) {
l.log("Ready! Port " + getLocalPort());
notifyEvent("openBaseClientResult", "ok");
} else {
l.log("Error!");
notifyEvent("openBaseClientResult", "error");
}
}
private static I2PSocketManager socketManager;
protected static synchronized I2PSocketManager getSocketManager() {
if (socketManager == null) {
socketManager = buildSocketManager();
}
return socketManager;
if (socketManager == null) {
socketManager = buildSocketManager();
}
return socketManager;
}
protected static I2PSocketManager buildSocketManager() {
Properties props = new Properties();
props.putAll(System.getProperties());
return I2PSocketManagerFactory.createManager
(I2PTunnel.host, Integer.parseInt(I2PTunnel.port), props);
Properties props = new Properties();
props.putAll(System.getProperties());
return I2PSocketManagerFactory.createManager(I2PTunnel.host, Integer.parseInt(I2PTunnel.port), props);
}
public final int getLocalPort() {
return localPort;
}
protected final InetAddress getListenHost(Logging l) {
try {
return InetAddress.getByName(I2PTunnel.listenHost);
} catch (UnknownHostException uhe) {
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;
}
try {
return InetAddress.getByName(I2PTunnel.listenHost);
} catch (UnknownHostException uhe) {
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;
}
}
/**
* Actually start working on incoming connections. *Must* be
* called by derived classes after initialization.
*
*/
public final void startRunning() {
synchronized (startLock) {
startRunning = true;
startLock.notify();
}
synchronized (startLock) {
startRunning = true;
startLock.notify();
}
}
/**
* create the default options (using the default timeout, etc)
*
*/
private I2PSocketOptions getDefaultOptions() {
I2PSocketOptions opts = new I2PSocketOptions();
opts.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
return opts;
I2PSocketOptions opts = new I2PSocketOptions();
opts.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
return opts;
}
/**
@ -162,7 +156,7 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
* @return a new I2PSocket
*/
public I2PSocket createI2PSocket(Destination dest) throws I2PException {
return createI2PSocket(dest, getDefaultOptions());
return createI2PSocket(dest, getDefaultOptions());
}
/**
@ -175,53 +169,53 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
* @return a new I2PSocket
*/
public I2PSocket createI2PSocket(Destination dest, I2PSocketOptions opt) throws I2PException {
I2PSocket i2ps;
I2PSocket i2ps;
synchronized (sockLock) {
i2ps = sockMgr.connect(dest, opt);
mySockets.add(i2ps);
}
synchronized (sockLock) {
i2ps = sockMgr.connect(dest, opt);
mySockets.add(i2ps);
}
return i2ps;
return i2ps;
}
public final void run() {
try {
InetAddress addr = getListenHost(l);
if (addr == null) return;
ss = new ServerSocket(localPort, 0, addr);
// If a free port was requested, find out what we got
if (localPort == 0) {
localPort = ss.getLocalPort();
}
notifyEvent("clientLocalPort", new Integer(ss.getLocalPort()));
l.log("Listening for clients on port " + localPort +
" of " + I2PTunnel.listenHost);
// Notify constructor that port is ready
synchronized(this) {
listenerReady = true;
notify();
}
try {
InetAddress addr = getListenHost(l);
if (addr == null) return;
ss = new ServerSocket(localPort, 0, addr);
// Wait until we are authorized to process data
synchronized (startLock) {
while (!startRunning) {
try {
startLock.wait();
} catch (InterruptedException ie) {}
}
}
// If a free port was requested, find out what we got
if (localPort == 0) {
localPort = ss.getLocalPort();
}
notifyEvent("clientLocalPort", new Integer(ss.getLocalPort()));
l.log("Listening for clients on port " + localPort + " of " + I2PTunnel.listenHost);
while (true) {
Socket s = ss.accept();
manageConnection(s);
}
} catch (IOException ex) {
_log.error("Error listening for connections", ex);
notifyEvent("openBaseClientResult", "error");
}
// Notify constructor that port is ready
synchronized (this) {
listenerReady = true;
notify();
}
// Wait until we are authorized to process data
synchronized (startLock) {
while (!startRunning) {
try {
startLock.wait();
} catch (InterruptedException ie) {
}
}
}
while (true) {
Socket s = ss.accept();
manageConnection(s);
}
} catch (IOException ex) {
_log.error("Error listening for connections", ex);
notifyEvent("openBaseClientResult", "error");
}
}
/**
@ -230,59 +224,58 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
* @param s Socket to take care of
*/
protected void manageConnection(Socket s) {
new ClientConnectionRunner(s, handlerName);
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) {
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());
}
return false;
}
l.log("Closing client "+toString());
try {
if (ss != null) ss.close();
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
l.log("Client closed.");
open=false;
return true;
}
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) {
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());
}
return false;
}
l.log("Closing client " + toString());
try {
if (ss != null) ss.close();
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
l.log("Client closed.");
open = false;
return true;
}
}
public static void closeSocket(Socket s) {
try {
s.close();
} catch (IOException ex) {
_log.error("Could not close socket", ex);
}
try {
s.close();
} catch (IOException ex) {
_log.error("Could not close socket", ex);
}
}
public class ClientConnectionRunner extends I2PThread {
private Socket s;
public ClientConnectionRunner(Socket s, String name) {
this.s=s;
setName(name);
start();
}
public void run() {
clientConnectionRun(s);
}
private Socket s;
public ClientConnectionRunner(Socket s, String name) {
this.s = s;
setName(name);
start();
}
public void run() {
clientConnectionRun(s);
}
}
/**
@ -290,4 +283,4 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
* you do not override manageConnection()
*/
protected abstract void clientConnectionRun(Socket s);
}
}

View File

@ -19,30 +19,30 @@ public class I2PTunnelGUI extends Frame implements ActionListener, Logging {
TextField input;
TextArea log;
I2PTunnel t;
public I2PTunnelGUI(I2PTunnel t) {
super("I2PTunnel control panel");
this.t=t;
setLayout(new BorderLayout());
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));
log.setFont(font);
log.setEditable(false);
log("enter 'help' for help.");
pack();
show();
super("I2PTunnel control panel");
this.t = t;
setLayout(new BorderLayout());
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));
log.setFont(font);
log.setEditable(false);
log("enter 'help' for help.");
pack();
show();
}
public void log(String s) {
log.append(s+"\n");
log.append(s + "\n");
}
public void actionPerformed(ActionEvent evt) {
log("I2PTunnel>"+input.getText());
t.runCommand(input.getText(), this);
log("---");
input.setText("");
log("I2PTunnel>" + input.getText());
t.runCommand(input.getText(), this);
log("---");
input.setText("");
}
}
}

View File

@ -19,17 +19,18 @@ 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,
// String wwwProxy) {
@ -37,299 +38,283 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase
// (EventDispatcher)null);
//}
public I2PTunnelHTTPClient(int localPort, Logging l,
boolean ownDest,
String wwwProxy, EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "HTTPHandler");
public I2PTunnelHTTPClient(int localPort, Logging l, boolean ownDest, String wwwProxy, EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "HTTPHandler");
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openHTTPClientResult", "error");
return;
}
this.wwwProxy = wwwProxy;
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openHTTPClientResult", "error");
return;
}
setName(getLocalPort()
+ " -> HTTPClient [WWW outproxy: " + this.wwwProxy + "]");
this.wwwProxy = wwwProxy;
startRunning();
setName(getLocalPort() + " -> HTTPClient [WWW outproxy: " + this.wwwProxy + "]");
notifyEvent("openHTTPClientResult", "ok");
startRunning();
notifyEvent("openHTTPClientResult", "ok");
}
protected void clientConnectionRun(Socket s) {
OutputStream out = null;
String targetRequest = null;
boolean usingWWWProxy = false;
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(" ");
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;
}
pos = request.indexOf("//");
if (pos == -1) {
method=null;
break;
}
protocol=request.substring(0,pos+2);
request=request.substring(pos+2);
OutputStream out = null;
String targetRequest = null;
boolean usingWWWProxy = false;
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(" ");
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;
}
pos = request.indexOf("//");
if (pos == -1) {
method = null;
break;
}
protocol = request.substring(0, pos + 2);
request = request.substring(pos + 2);
targetRequest = request;
targetRequest = request;
pos = request.indexOf("/");
if (pos == -1) {
method=null;
break;
}
host=request.substring(0,pos);
pos = request.indexOf("/");
if (pos == -1) {
method = null;
break;
}
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);
} else if (host.indexOf(".") != -1) {
// The request must be forwarded to a WWW proxy
destination = wwwProxy;
usingWWWProxy = true;
} else {
request=request.substring(pos+1);
pos = request.indexOf("/");
destination=request.substring(0,pos);
line=method+" "+request.substring(pos);
}
// Quick hack for foo.bar.i2p
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);
pos = request.indexOf("/");
destination = request.substring(0, pos);
line = method + " " + request.substring(pos);
}
boolean isValid = usingWWWProxy ||
isSupportedAddress(host, protocol);
if (!isValid) {
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
}
boolean isValid = usingWWWProxy || isSupportedAddress(host, protocol);
if (!isValid) {
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.DEBUG)) {
_log.debug("METHOD:"+method+":");
_log.debug("PROTOC:"+protocol+":");
_log.debug("HOST :"+host+":");
_log.debug("DEST :"+destination+":");
}
if (_log.shouldLog(Log.DEBUG)) {
_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);
}
newRequest.append(line).append("\r\n"); // HTTP spec
if (line.length()==0) break;
}
while (br.ready()) { // empty the buffer (POST requests)
int i=br.read();
if (i != -1) {
newRequest.append((char)i);
}
}
if (method==null || destination==null) {
l.log("No HTTP method found in the request.");
if (out != null) {
out.write(ERR_REQUEST_DENIED);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
Destination dest=I2PTunnel.destFromName(destination);
if (dest == null) {
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");
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);
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);
closeSocket(s);
}
} else if (line.startsWith("Host: ") && !usingWWWProxy) {
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;
}
while (br.ready()) { // empty the buffer (POST requests)
int i = br.read();
if (i != -1) {
newRequest.append((char) i);
}
}
if (method == null || destination == null) {
l.log("No HTTP method found in the request.");
if (out != null) {
out.write(ERR_REQUEST_DENIED);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
Destination dest = I2PTunnel.destFromName(destination);
if (dest == null) {
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");
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);
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);
closeSocket(s);
}
}
private static final long INACTIVITY_TIMEOUT = 120*1000;
private static final long INACTIVITY_TIMEOUT = 120 * 1000;
private class InactivityTimeoutThread extends I2PThread {
private Socket s;
private I2PTunnelRunner _runner;
private OutputStream _out;
private String _targetRequest;
private boolean _useWWWProxy;
private boolean _disabled;
private Object _disableLock = new Object();
public InactivityTimeoutThread(I2PTunnelRunner runner, OutputStream out, String targetRequest, boolean useWWWProxy, Socket s) {
this.s=s;
_runner = runner;
_out = out;
_targetRequest = targetRequest;
_useWWWProxy = useWWWProxy;
_disabled = false;
setName("InactivityThread");
}
public void disable() {
_disabled = true;
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");
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()) + ")");
timeout();
return;
} else {
// runner hasn't been going to long enough
}
} else {
// there has been activity in the period
}
synchronized (_disableLock) {
try {
_disableLock.wait(INACTIVITY_TIMEOUT);
} catch (InterruptedException ie) {}
}
}
}
private void timeout() {
_log.info("Inactivity timeout reached");
l.log("Inactivity timeout reached");
if (_out != null) {
try {
if (_runner.getLastActivityOn() > 0) {
// some data has been sent, so don't 404 it
} else {
writeErrorMessage(ERR_TIMEOUT, _out, _targetRequest,
_useWWWProxy, wwwProxy);
}
} catch (IOException ioe) {
_log.warn("Error writing out the 'timeout' message", ioe);
}
} else {
_log.warn("Client disconnected before we could say we timed out");
}
closeSocket(s);
}
private Socket s;
private I2PTunnelRunner _runner;
private OutputStream _out;
private String _targetRequest;
private boolean _useWWWProxy;
private boolean _disabled;
private Object _disableLock = new Object();
public InactivityTimeoutThread(I2PTunnelRunner runner, OutputStream out, String targetRequest,
boolean useWWWProxy, Socket s) {
this.s = s;
_runner = runner;
_out = out;
_targetRequest = targetRequest;
_useWWWProxy = useWWWProxy;
_disabled = false;
setName("InactivityThread");
}
public void disable() {
_disabled = true;
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");
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()) + ")");
timeout();
return;
} else {
// runner hasn't been going to long enough
}
} else {
// there has been activity in the period
}
synchronized (_disableLock) {
try {
_disableLock.wait(INACTIVITY_TIMEOUT);
} catch (InterruptedException ie) {
}
}
}
}
private void timeout() {
_log.info("Inactivity timeout reached");
l.log("Inactivity timeout reached");
if (_out != null) {
try {
if (_runner.getLastActivityOn() > 0) {
// some data has been sent, so don't 404 it
} else {
writeErrorMessage(ERR_TIMEOUT, _out, _targetRequest, _useWWWProxy, wwwProxy);
}
} catch (IOException ioe) {
_log.warn("Error writing out the 'timeout' message", ioe);
}
} else {
_log.warn("Client disconnected before we could say we timed out");
}
closeSocket(s);
}
}
private final static String getHostName(String host) {
try {
Destination dest=I2PTunnel.destFromName(host);
if (dest == null) return "i2p";
return dest.toBase64();
} catch (DataFormatException dfe) {
return "i2p";
}
}
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());
}
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
try {
Destination dest = I2PTunnel.destFromName(host);
if (dest == null) return "i2p";
return dest.toBase64();
} catch (DataFormatException dfe) {
return "i2p";
}
}
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);
} catch (IOException 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);
}
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());
}
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
}
private final static String SUPPORTED_HOSTS[] = { "i2p", "www.i2p.com",
"i2p." };
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);
} catch (IOException 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);
}
}
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;
boolean found = false;
String lcHost = host.toLowerCase();
for (int i = 0; i < SUPPORTED_HOSTS.length; i++) {
if (SUPPORTED_HOSTS[i].equals(lcHost)) {
found = true;
break;
}
}
if ((host == null) || (protocol == null)) return false;
boolean found = false;
String lcHost = host.toLowerCase();
for (int i = 0; i < SUPPORTED_HOSTS.length; i++) {
if (SUPPORTED_HOSTS[i].equals(lcHost)) {
found = true;
break;
}
}
if (!found) {
try {
Destination d = I2PTunnel.destFromName(host);
if (d == null) return false;
} catch (DataFormatException dfe) {}
}
return protocol.equalsIgnoreCase("http://");
if (!found) {
try {
Destination d = I2PTunnel.destFromName(host);
if (d == null) return false;
} catch (DataFormatException dfe) {
}
}
return protocol.equalsIgnoreCase("http://");
}
}
}

View File

@ -19,21 +19,21 @@ import net.i2p.util.Log;
public class I2PTunnelRunner extends I2PThread {
private final static Log _log = new Log(I2PTunnelRunner.class);
/**
* max bytes streamed in a packet - smaller ones might be filled
* up to this size. Larger ones are not split (at least not on
* 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,17 +42,16 @@ 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;
this.initialData = initialData;
lastActivityOn = -1;
startedOn = -1;
_log.info("I2PTunnelRunner started");
setName("I2PTunnelRunner");
start();
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;
_log.info("I2PTunnelRunner started");
setName("I2PTunnelRunner");
start();
}
/**
@ -60,127 +59,133 @@ 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?
*
* @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);
InputStream i2pin = i2ps.getInputStream();
OutputStream i2pout = new BufferedOutputStream
(i2ps.getOutputStream(), MAX_PACKET_SIZE);
if (initialData != null) {
synchronized(slock) {
i2pout.write(initialData);
i2pout.flush();
}
}
Thread t1 = new StreamForwarder(in, i2pout);
Thread t2 = new StreamForwarder(i2pin, out);
synchronized(finishLock) {
while (!finished) {
finishLock.wait();
}
}
// now one connection is dead - kill the other as well.
s.close();
s = null;
i2ps.close();
i2ps = null;
t1.join();
t2.join();
} catch (InterruptedException ex) {
_log.error("Interrupted", ex);
} catch (IOException ex) {
ex.printStackTrace();
_log.error("Error forwarding", ex);
} finally {
try {
if (s != null) s.close();
if (i2ps != null) i2ps.close();
} catch (IOException ex) {
ex.printStackTrace();
_log.error("Could not close socket", ex);
}
}
startedOn = Clock.getInstance().now();
try {
InputStream in = s.getInputStream();
OutputStream out = new BufferedOutputStream(s.getOutputStream(), NETWORK_BUFFER_SIZE);
InputStream i2pin = i2ps.getInputStream();
OutputStream i2pout = new BufferedOutputStream(i2ps.getOutputStream(), MAX_PACKET_SIZE);
if (initialData != null) {
synchronized (slock) {
i2pout.write(initialData);
i2pout.flush();
}
}
Thread t1 = new StreamForwarder(in, i2pout);
Thread t2 = new StreamForwarder(i2pin, out);
synchronized (finishLock) {
while (!finished) {
finishLock.wait();
}
}
// now one connection is dead - kill the other as well.
s.close();
s = null;
i2ps.close();
i2ps = null;
t1.join();
t2.join();
} catch (InterruptedException ex) {
_log.error("Interrupted", ex);
} catch (IOException ex) {
ex.printStackTrace();
_log.error("Error forwarding", ex);
} finally {
try {
if (s != null) s.close();
if (i2ps != null) i2ps.close();
} catch (IOException ex) {
ex.printStackTrace();
_log.error("Could not close socket", ex);
}
}
}
private class StreamForwarder extends I2PThread {
InputStream in;
OutputStream out;
private StreamForwarder(InputStream in, OutputStream out) {
this.in=in;
this.out=out;
setName("StreamForwarder");
start();
}
InputStream in;
OutputStream out;
public void run() {
byte[] buffer = new byte[NETWORK_BUFFER_SIZE];
try {
int len;
while ((len=in.read(buffer)) != -1) {
out.write(buffer, 0, len);
if (len > 0)
updateActivity();
if (in.available()==0) {
try {
Thread.sleep(I2PTunnel.PACKET_DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
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) {
if (!finished)
_log.error("Error reading and writing", ex);
else
_log.warn("You may ignore this", ex);
}
} catch (IOException ex) {
if (!finished)
_log.error("Error forwarding", ex);
else
_log.warn("You may ignore this", ex);
} finally {
try {
out.close();
in.close();
} catch (IOException ex) {
_log.error("Error closing streams", ex);
}
synchronized(finishLock) {
finished=true;
finishLock.notifyAll();
// the main thread will close sockets etc. now
}
}
}
}
}
private StreamForwarder(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
setName("StreamForwarder");
start();
}
public void run() {
byte[] buffer = new byte[NETWORK_BUFFER_SIZE];
try {
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
if (len > 0) updateActivity();
if (in.available() == 0) {
try {
Thread.sleep(I2PTunnel.PACKET_DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
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) {
if (!finished)
_log.error("Error reading and writing", ex);
else
_log.warn("You may ignore this", ex);
}
} catch (IOException ex) {
if (!finished)
_log.error("Error forwarding", ex);
else
_log.warn("You may ignore this", ex);
} finally {
try {
out.close();
in.close();
} catch (IOException ex) {
_log.error("Error closing streams", ex);
}
synchronized (finishLock) {
finished = true;
finishLock.notifyAll();
// the main thread will close sockets etc. now
}
}
}
}
}

View File

@ -26,9 +26,8 @@ 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);
private I2PSocketManager sockMgr;
@ -40,101 +39,93 @@ public class I2PTunnelServer extends I2PTunnelTask
private int remotePort;
private Logging l;
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);
try {
init(host, port, new FileInputStream(privkey), privkeyname, l);
} catch (IOException ioe) {
_log.error("Error starting server", ioe);
notifyEvent("openServerResult", "error");
}
}
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;
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);
}
l.log("Ready!");
notifyEvent("openServerResult", "ok");
open=true;
Thread t = new I2PThread(this);
t.setName("Server");
t.start();
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);
try {
init(host, port, new FileInputStream(privkey), privkeyname, l);
} catch (IOException ioe) {
_log.error("Error starting server", ioe);
notifyEvent("openServerResult", "error");
}
}
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;
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);
}
l.log("Ready!");
notifyEvent("openServerResult", "ok");
open = true;
Thread t = new I2PThread(this);
t.setName("Server");
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();) {
l.log("->"+it.next());
}
return false;
}
l.log("Shutting down server "+toString());
try {
if (i2pss != null) i2pss.close();
sockMgr.getSession().destroySession();
} catch (I2PException ex) {
_log.error("Error destroying the session", ex);
System.exit(1);
}
l.log("Server shut down.");
open=false;
return true;
}
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();) {
l.log("->" + it.next());
}
return false;
}
l.log("Shutting down server " + toString());
try {
if (i2pss != null) i2pss.close();
sockMgr.getSession().destroySession();
} catch (I2PException ex) {
_log.error("Error destroying the session", ex);
System.exit(1);
}
l.log("Server shut down.");
open = false;
return true;
}
}
public void run() {
try {
I2PServerSocket i2pss = sockMgr.getServerSocket();
while (true) {
I2PSocket i2ps = i2pss.accept();
//local is fast, so synchronously. Does not need that many
//threads.
try {
Socket s = new Socket(remoteHost, remotePort);
new I2PTunnelRunner(s, i2ps, slock, null);
} catch (SocketException ex) {
i2ps.close();
}
}
} catch (I2PException ex) {
_log.error("Error while waiting for I2PConnections", ex);
} catch (IOException ex) {
_log.error("Error while waiting for I2PConnections", ex);
}
}
try {
I2PServerSocket i2pss = sockMgr.getServerSocket();
while (true) {
I2PSocket i2ps = i2pss.accept();
//local is fast, so synchronously. Does not need that many
//threads.
try {
Socket s = new Socket(remoteHost, remotePort);
new I2PTunnelRunner(s, i2ps, slock, null);
} catch (SocketException ex) {
i2ps.close();
}
}
} catch (I2PException ex) {
_log.error("Error while waiting for I2PConnections", ex);
} catch (IOException ex) {
_log.error("Error while waiting for I2PConnections", ex);
}
}
}

View File

@ -27,49 +27,86 @@ public abstract class I2PTunnelTask implements EventDispatcher {
//}
protected I2PTunnelTask(String name, EventDispatcher notifyThis) {
attachEventDispatcher(notifyThis);
this.name=name;
this.id = -1;
attachEventDispatcher(notifyThis);
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;
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

@ -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;
@ -40,190 +40,183 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
private int simulPings = 0;
private long lastPingTime = 0;
private Object lock = new Object(), slock = new Object();
private Object lock = new Object(), slock = new Object();
//public I2Ping(String cmd, Logging l,
// boolean ownDest) {
// 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) {
if (ownDest) {
sockMgr = I2PTunnelClient.buildSocketManager();
} else {
sockMgr = I2PTunnelClient.getSocketManager();
}
}
Thread t = new I2PThread(this);
t.setName("Client");
t.start();
open=true;
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 {
sockMgr = I2PTunnelClient.getSocketManager();
}
}
Thread t = new I2PThread(this);
t.setName("Client");
t.start();
open = true;
}
public void run() {
l.log("*** I2Ping results:");
try {
runCommand(command);
} catch (InterruptedException ex) {
l.log("*** Interrupted");
_log.error("Pinger interrupted",ex);
} catch (IOException ex) {
_log.error("Pinger exception",ex);
}
l.log("*** Finished.");
synchronized(lock) {
finished=true;
}
close(false);
l.log("*** I2Ping results:");
try {
runCommand(command);
} catch (InterruptedException ex) {
l.log("*** Interrupted");
_log.error("Pinger interrupted", ex);
} catch (IOException ex) {
_log.error("Pinger exception", ex);
}
l.log("*** Finished.");
synchronized (lock) {
finished = true;
}
close(false);
}
public void runCommand(String cmd) throws InterruptedException,
IOException {
if (cmd.startsWith("-t ")) { // timeout
cmd = cmd.substring(3);
int pos = cmd.indexOf(" ");
if (pos == -1) {
l.log("Syntax error");
return;
} else {
timeout = Long.parseLong(cmd.substring(0, pos));
cmd=cmd.substring(pos+1);
}
}
if (cmd.startsWith("-m ")) { // max simultaneous pings
cmd = cmd.substring(3);
int pos = cmd.indexOf(" ");
if (pos == -1) {
l.log("Syntax error");
return;
} else {
MAX_SIMUL_PINGS = Integer.parseInt(cmd.substring(0, pos));
cmd=cmd.substring(pos+1);
}
}
if (cmd.startsWith("-c ")) { // "count" ping
countPing=true;
cmd=cmd.substring(3);
}
if (cmd.equals("-h")) { // ping all hosts
cmd="-l hosts.txt";
}
if (cmd.startsWith("-l ")) { // ping a list of hosts
BufferedReader br = new BufferedReader
(new FileReader(cmd.substring(3)));
String line;
List pingHandlers = new ArrayList();
while ((line = br.readLine()) != null) {
if (line.startsWith("#")) continue; // comments
if (line.startsWith(";")) continue;
if (line.startsWith("!")) continue;
if (line.indexOf("=") != -1) { // maybe file is hosts.txt?
line=line.substring(0,line.indexOf("="));
}
pingHandlers.add(new PingHandler(line));
}
br.close();
for (Iterator it= pingHandlers.iterator(); it.hasNext(); ) {
Thread t = (Thread) it.next();
t.join();
}
public void runCommand(String cmd) throws InterruptedException, IOException {
if (cmd.startsWith("-t ")) { // timeout
cmd = cmd.substring(3);
int pos = cmd.indexOf(" ");
if (pos == -1) {
l.log("Syntax error");
return;
} else {
timeout = Long.parseLong(cmd.substring(0, pos));
cmd = cmd.substring(pos + 1);
}
}
if (cmd.startsWith("-m ")) { // max simultaneous pings
cmd = cmd.substring(3);
int pos = cmd.indexOf(" ");
if (pos == -1) {
l.log("Syntax error");
return;
} else {
MAX_SIMUL_PINGS = Integer.parseInt(cmd.substring(0, pos));
cmd = cmd.substring(pos + 1);
}
}
if (cmd.startsWith("-c ")) { // "count" ping
countPing = true;
cmd = cmd.substring(3);
}
if (cmd.equals("-h")) { // ping all hosts
cmd = "-l hosts.txt";
}
if (cmd.startsWith("-l ")) { // ping a list of hosts
BufferedReader br = new BufferedReader(new FileReader(cmd.substring(3)));
String line;
List pingHandlers = new ArrayList();
while ((line = br.readLine()) != null) {
if (line.startsWith("#")) continue; // comments
if (line.startsWith(";")) continue;
if (line.startsWith("!")) continue;
if (line.indexOf("=") != -1) { // maybe file is hosts.txt?
line = line.substring(0, line.indexOf("="));
}
pingHandlers.add(new PingHandler(line));
}
br.close();
for (Iterator it = pingHandlers.iterator(); it.hasNext();) {
Thread t = (Thread) it.next();
t.join();
}
} else {
Thread t = new PingHandler(cmd);
t.join();
}
} else {
Thread t = new PingHandler(cmd);
t.join();
}
}
public boolean close(boolean forced) {
if (!open) return true;
synchronized(lock) {
if (!forced && !finished) {
l.log("There are still pings running!");
return false;
}
l.log("Closing pinger "+toString());
l.log("Pinger closed.");
open=false;
return true;
}
if (!open) return true;
synchronized (lock) {
if (!forced && !finished) {
l.log("There are still pings running!");
return false;
}
l.log("Closing pinger " + toString());
l.log("Pinger closed.");
open = false;
return true;
}
}
public boolean ping(Destination dest) throws I2PException {
try {
synchronized(simulLock) {
while (simulPings >= MAX_SIMUL_PINGS) {
simulLock.wait();
}
simulPings++;
while (lastPingTime + PING_DISTANCE >
System.currentTimeMillis()) {
// no wait here, to delay all pingers
Thread.sleep(PING_DISTANCE/2);
}
lastPingTime=System.currentTimeMillis();
}
boolean sent = sockMgr.ping(dest, PING_TIMEOUT);
synchronized(simulLock) {
simulPings--;
simulLock.notifyAll();
}
return sent;
} catch (InterruptedException ex) {
_log.error("Interrupted", ex);
return false;
}
try {
synchronized (simulLock) {
while (simulPings >= MAX_SIMUL_PINGS) {
simulLock.wait();
}
simulPings++;
while (lastPingTime + PING_DISTANCE > System.currentTimeMillis()) {
// no wait here, to delay all pingers
Thread.sleep(PING_DISTANCE / 2);
}
lastPingTime = System.currentTimeMillis();
}
boolean sent = sockMgr.ping(dest, PING_TIMEOUT);
synchronized (simulLock) {
simulPings--;
simulLock.notifyAll();
}
return sent;
} catch (InterruptedException ex) {
_log.error("Interrupted", ex);
return false;
}
}
public class PingHandler extends I2PThread {
private String destination;
public PingHandler(String dest) {
this.destination=dest;
setName("PingHandler for " + dest);
start();
}
public void run() {
try {
Destination dest=I2PTunnel.destFromName(destination);
if (dest == null) {
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++) {
boolean sent;
sent = ping(dest);
if (countPing) {
if (!sent) {
pingResults.append(i).append(" ");
break;
} else if (i == cnt - 1) {
pingResults.append("+ ");
}
} else {
pingResults.append(sent?"+ ":"- ");
}
// System.out.println(sent+" -> "+destination);
}
pingResults.append(" ").append(destination);
synchronized(lock) { // Logger is not thread safe
l.log(pingResults.toString());
}
} catch (I2PException ex) {
_log.error("Error pinging " + destination, ex);
}
}
private String destination;
public PingHandler(String dest) {
this.destination = dest;
setName("PingHandler for " + dest);
start();
}
public void run() {
try {
Destination dest = I2PTunnel.destFromName(destination);
if (dest == null) {
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++) {
boolean sent;
sent = ping(dest);
if (countPing) {
if (!sent) {
pingResults.append(i).append(" ");
break;
} else if (i == cnt - 1) {
pingResults.append("+ ");
}
} else {
pingResults.append(sent ? "+ " : "- ");
}
// System.out.println(sent+" -> "+destination);
}
pingResults.append(" ").append(destination);
synchronized (lock) { // Logger is not thread safe
l.log(pingResults.toString());
}
} catch (I2PException ex) {
_log.error("Error pinging " + destination, ex);
}
}
}
}
}

View File

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

View File

@ -151,283 +151,285 @@ public class TunnelManager implements Runnable {
private I2PTunnel _tunnel;
private ServerSocket _socket;
private boolean _keepAccepting;
public TunnelManager(int listenPort) {
this(null, listenPort);
this(null, listenPort);
}
public TunnelManager(String listenHost, int listenPort) {
_tunnel = new I2PTunnel();
_keepAccepting = true;
try {
if (listenHost != null) {
_socket = new ServerSocket(listenPort, 0, InetAddress.getByName(listenHost));
_log.info("Listening for tunnel management clients on " + listenHost + ":" + listenPort);
} else {
_socket = new ServerSocket(listenPort);
_log.info("Listening for tunnel management clients on localhost:" + listenPort);
}
} catch (Exception e) {
_log.error("Error starting up tunnel management listener on " + listenPort, e);
}
_tunnel = new I2PTunnel();
_keepAccepting = true;
try {
if (listenHost != null) {
_socket = new ServerSocket(listenPort, 0, InetAddress.getByName(listenHost));
_log.info("Listening for tunnel management clients on " + listenHost + ":" + listenPort);
} else {
_socket = new ServerSocket(listenPort);
_log.info("Listening for tunnel management clients on localhost:" + listenPort);
}
} catch (Exception e) {
_log.error("Error starting up tunnel management listener on " + listenPort, e);
}
}
public static void main(String args[]) {
int port = 7676;
String host = null;
if (args.length == 1) {
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException nfe) {
_log.error("Usage: TunnelManager [host] [port]");
return;
}
} else if (args.length == 2) {
host = args[0];
try {
port = Integer.parseInt(args[1]);
} catch (NumberFormatException nfe) {
_log.error("Usage: TunnelManager [host] [port]");
return;
}
}
int port = 7676;
String host = null;
if (args.length == 1) {
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException nfe) {
_log.error("Usage: TunnelManager [host] [port]");
return;
}
} else if (args.length == 2) {
host = args[0];
try {
port = Integer.parseInt(args[1]);
} catch (NumberFormatException nfe) {
_log.error("Usage: TunnelManager [host] [port]");
return;
}
}
TunnelManager mgr = new TunnelManager(host, port);
Thread t = new I2PThread(mgr, "Listener");
t.start();
TunnelManager mgr = new TunnelManager(host, port);
Thread t = new I2PThread(mgr, "Listener");
t.start();
}
public void run() {
if (_socket == null) {
_log.error("Unable to start listening, since the socket was not bound. Already running?");
return;
}
_log.debug("Running");
try {
while (_keepAccepting) {
Socket socket = _socket.accept();
_log.debug("Client accepted");
if (socket != null) {
Thread t = new I2PThread(new TunnelManagerClientRunner(this, socket));
t.setName("TunnelManager Client");
t.setPriority(I2PThread.MIN_PRIORITY);
t.start();
}
}
} catch (IOException ioe) {
_log.error("Error accepting connections", ioe);
} catch (Exception e) {
_log.error("Other error?!", e);
} finally {
if (_socket != null) try { _socket.close(); } catch (IOException ioe) {}
}
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
if (_socket == null) {
_log.error("Unable to start listening, since the socket was not bound. Already running?");
return;
}
_log.debug("Running");
try {
while (_keepAccepting) {
Socket socket = _socket.accept();
_log.debug("Client accepted");
if (socket != null) {
Thread t = new I2PThread(new TunnelManagerClientRunner(this, socket));
t.setName("TunnelManager Client");
t.setPriority(I2PThread.MIN_PRIORITY);
t.start();
}
}
} catch (IOException ioe) {
_log.error("Error accepting connections", ioe);
} catch (Exception e) {
_log.error("Other error?!", e);
} finally {
if (_socket != null) try {
_socket.close();
} catch (IOException ioe) {
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
}
public void error(String msg, OutputStream out) throws IOException {
out.write(msg.getBytes());
out.write('\n');
out.write(msg.getBytes());
out.write('\n');
}
public void processQuit(OutputStream out) throws IOException {
out.write("Nice try".getBytes());
out.write('\n');
out.write("Nice try".getBytes());
out.write('\n');
}
public void processList(OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
long startCommand = Clock.getInstance().now();
_tunnel.runCommand("list", buf);
Object obj = _tunnel.waitEventValue("listDone");
long endCommand = Clock.getInstance().now();
String str = buf.getBuffer();
_log.debug("ListDone complete after " + (endCommand-startCommand) + "ms: [" + str + "]");
out.write(str.getBytes());
out.write('\n');
buf.ignoreFurtherActions();
BufferLogger buf = new BufferLogger();
long startCommand = Clock.getInstance().now();
_tunnel.runCommand("list", buf);
Object obj = _tunnel.waitEventValue("listDone");
long endCommand = Clock.getInstance().now();
String str = buf.getBuffer();
_log.debug("ListDone complete after " + (endCommand - startCommand) + "ms: [" + str + "]");
out.write(str.getBytes());
out.write('\n');
buf.ignoreFurtherActions();
}
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");
out.write((status + "\n").getBytes());
buf.ignoreFurtherActions();
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("listen_on " + ip, buf);
String status = (String) _tunnel.waitEventValue("listen_onResult");
out.write((status + "\n").getBytes());
buf.ignoreFurtherActions();
}
/**
* "lookup <name>" returns with the result in base64, else "Unknown host" [or something like that],
* then a newline.
*
*/
public void processLookup(String name, OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("lookup " + name, buf);
String rv = (String)_tunnel.waitEventValue("lookupResult");
out.write(rv.getBytes());
out.write('\n');
buf.ignoreFurtherActions();
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("lookup " + name, buf);
String rv = (String) _tunnel.waitEventValue("lookupResult");
out.write(rv.getBytes());
out.write('\n');
buf.ignoreFurtherActions();
}
public void processTestDestination(String destKey, OutputStream out) throws IOException {
try {
Destination d = new Destination();
d.fromBase64(destKey);
out.write("valid\n".getBytes());
} catch (DataFormatException dfe) {
out.write("invalid\n".getBytes());
}
out.flush();
try {
Destination d = new Destination();
d.fromBase64(destKey);
out.write("valid\n".getBytes());
} catch (DataFormatException dfe) {
out.write("invalid\n".getBytes());
}
out.flush();
}
public void processConvertPrivate(String priv, OutputStream out) throws IOException {
try {
Destination dest = new Destination();
dest.fromBase64(priv);
String str = dest.toBase64();
out.write(str.getBytes());
out.write('\n');
} catch (DataFormatException dfe) {
_log.error("Error converting private data", dfe);
out.write("Error converting private key\n".getBytes());
}
try {
Destination dest = new Destination();
dest.fromBase64(priv);
String str = dest.toBase64();
out.write(str.getBytes());
out.write('\n');
} catch (DataFormatException dfe) {
_log.error("Error converting private data", dfe);
out.write("Error converting private key\n".getBytes());
}
}
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");
out.write((str + "\n").getBytes());
buf.ignoreFurtherActions();
BufferLogger buf = new BufferLogger();
_tunnel.runCommand((forced ? "close forced " : "close ") + which, buf);
String str = (String) _tunnel.waitEventValue("closeResult");
out.write((str + "\n").getBytes());
buf.ignoreFurtherActions();
}
/**
* "genkey" returns with the base64 of the destination, followed by a tab, then the base64 of that
* destination's private keys, then a newline.
*
*/
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");
out.write((pub + "\t" + priv).getBytes());
out.write('\n');
buf.ignoreFurtherActions();
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("gentextkeys", buf);
String priv = (String) _tunnel.waitEventValue("privateKey");
String pub = (String) _tunnel.waitEventValue("publicDestination");
out.write((pub + "\t" + priv).getBytes());
out.write('\n');
buf.ignoreFurtherActions();
}
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");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String)_tunnel.waitEventValue("openClientResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("client " + listenPort + " " + peer, buf);
Integer taskId = (Integer) _tunnel.waitEventValue("clientTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String) _tunnel.waitEventValue("openClientResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
Integer port = (Integer)_tunnel.waitEventValue("clientLocalPort");
out.write((rv + " " + port.intValue() + " [" + taskId.intValue()
+ "]\n").getBytes());
buf.ignoreFurtherActions();
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
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 {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("httpclient " + listenPort + " " + proxy, buf);
Integer taskId = (Integer)_tunnel.waitEventValue("httpclientTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String)_tunnel.waitEventValue("openHTTPClientResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
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");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String) _tunnel.waitEventValue("openHTTPClientResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
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 {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("sockstunnel " + listenPort, buf);
Integer taskId = (Integer)_tunnel.waitEventValue("sockstunnelTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String)_tunnel.waitEventValue("openSOCKSTunnelResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
Integer port = (Integer)_tunnel.waitEventValue("clientLocalPort");
out.write((rv + " " + port.intValue() + " [" + taskId.intValue()
+ "]\n").getBytes());
buf.ignoreFurtherActions();
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
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 {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("textserver " + serverHost + " " + serverPort + " " + privateKeys, buf);
Integer taskId = (Integer)_tunnel.waitEventValue("serverTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String)_tunnel.waitEventValue("openServerResult");
public void processOpenSOCKSTunnel(int listenPort, OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("sockstunnel " + listenPort, buf);
Integer taskId = (Integer) _tunnel.waitEventValue("sockstunnelTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String) _tunnel.waitEventValue("openSOCKSTunnelResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
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 {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("textserver " + serverHost + " " + serverPort + " " + privateKeys, buf);
Integer taskId = (Integer) _tunnel.waitEventValue("serverTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String) _tunnel.waitEventValue("openServerResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
}
/**
* Frisbee.
*
*/
public void unknownCommand(String command, OutputStream out) throws IOException {
out.write("Unknown command: ".getBytes());
out.write(command.getBytes());
out.write("\n".getBytes());
out.write("Unknown command: ".getBytes());
out.write(command.getBytes());
out.write("\n".getBytes());
}
}
}

View File

@ -21,172 +21,174 @@ class TunnelManagerClientRunner implements Runnable {
private final static Log _log = new Log(TunnelManagerClientRunner.class);
private TunnelManager _mgr;
private Socket _clientSocket;
public TunnelManagerClientRunner(TunnelManager mgr, Socket socket) {
_clientSocket = socket;
_mgr = mgr;
}
public void run() {
_log.debug("Client running");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(_clientSocket.getInputStream()));
OutputStream out = _clientSocket.getOutputStream();
String cmd = reader.readLine();
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) {}
}
_log.debug("Client closed");
public TunnelManagerClientRunner(TunnelManager mgr, Socket socket) {
_clientSocket = socket;
_mgr = mgr;
}
public void run() {
_log.debug("Client running");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(_clientSocket.getInputStream()));
OutputStream out = _clientSocket.getOutputStream();
String cmd = reader.readLine();
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) {
}
}
_log.debug("Client closed");
}
/**
* Parse the command string and fire off the appropriate tunnelManager method,
* sending the results to the output stream
*/
private void processCommand(String command, OutputStream out) throws IOException {
_log.debug("Processing [" + command + "]");
StringTokenizer tok = new StringTokenizer(command);
if (!tok.hasMoreTokens()) {
_mgr.unknownCommand(command, out);
} else {
String cmd = tok.nextToken();
if ("quit".equalsIgnoreCase(cmd)) {
_mgr.processQuit(out);
} else if ("lookup".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processLookup(tok.nextToken(), out);
else
_mgr.error("Usage: lookup <hostname>", out);
} else if ("testdestination".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processTestDestination(tok.nextToken(), out);
else
_mgr.error("Usage: testdestination <publicDestination>", out);
} else if ("convertprivate".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processConvertPrivate(tok.nextToken(), out);
else
_mgr.error("Usage: convertprivate <privateData>", out);
} else if ("close".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens()) {
String closeArg;
if ((closeArg = tok.nextToken()).equals("forced")) {
if (tok.hasMoreTokens()) {
_mgr.processClose(tok.nextToken(), true, out);
} else {
_mgr.error("Usage: close [forced] <jobnumber>|all", out);
}
} else {
_mgr.processClose(closeArg, false, out);
}
} else {
_mgr.error("Usage: close [forced] <jobnumber>|all", out);
}
} else if ("genkey".equalsIgnoreCase(cmd)) {
_mgr.processGenKey(out);
} else if ("list".equalsIgnoreCase(cmd)) {
_mgr.processList(out);
} else if ("listen_on".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens()) {
_mgr.processListenOn(tok.nextToken(), out);
} else {
_mgr.error("Usage: listen_on <ip>", out);
}
} else if ("openclient".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String peer = null;
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openclient <listenPort> <peer>", out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openclient <listenport> <peer>", out);
return;
}
peer = tok.nextToken();
_mgr.processOpenClient(listenPort, peer, out);
} else if ("openhttpclient".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String proxy = "squid.i2p";
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openhttpclient <listenPort> [<proxy>]",out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (tok.hasMoreTokens()) {
proxy = tok.nextToken();
}
if (tok.hasMoreTokens()) {
_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);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (tok.hasMoreTokens()) {
_mgr.error("Usage: opensockstunnel <listenport>",out);
return;
}
_mgr.processOpenSOCKSTunnel(listenPort, out);
} else if ("openserver".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String serverHost = null;
String serverKeys = null;
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
serverHost = tok.nextToken();
_log.debug("Processing [" + command + "]");
StringTokenizer tok = new StringTokenizer(command);
if (!tok.hasMoreTokens()) {
_mgr.unknownCommand(command, out);
} else {
String cmd = tok.nextToken();
if ("quit".equalsIgnoreCase(cmd)) {
_mgr.processQuit(out);
} else if ("lookup".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processLookup(tok.nextToken(), out);
else
_mgr.error("Usage: lookup <hostname>", out);
} else if ("testdestination".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processTestDestination(tok.nextToken(), out);
else
_mgr.error("Usage: testdestination <publicDestination>", out);
} else if ("convertprivate".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processConvertPrivate(tok.nextToken(), out);
else
_mgr.error("Usage: convertprivate <privateData>", out);
} else if ("close".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens()) {
String closeArg;
if ((closeArg = tok.nextToken()).equals("forced")) {
if (tok.hasMoreTokens()) {
_mgr.processClose(tok.nextToken(), true, out);
} else {
_mgr.error("Usage: close [forced] <jobnumber>|all", out);
}
} else {
_mgr.processClose(closeArg, false, out);
}
} else {
_mgr.error("Usage: close [forced] <jobnumber>|all", out);
}
} else if ("genkey".equalsIgnoreCase(cmd)) {
_mgr.processGenKey(out);
} else if ("list".equalsIgnoreCase(cmd)) {
_mgr.processList(out);
} else if ("listen_on".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens()) {
_mgr.processListenOn(tok.nextToken(), out);
} else {
_mgr.error("Usage: listen_on <ip>", out);
}
} else if ("openclient".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String peer = null;
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openclient <listenPort> <peer>", out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openclient <listenport> <peer>", out);
return;
}
peer = tok.nextToken();
_mgr.processOpenClient(listenPort, peer, out);
} else if ("openhttpclient".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String proxy = "squid.i2p";
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openhttpclient <listenPort> [<proxy>]", out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (tok.hasMoreTokens()) {
proxy = tok.nextToken();
}
if (tok.hasMoreTokens()) {
_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);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (tok.hasMoreTokens()) {
_mgr.error("Usage: opensockstunnel <listenport>", out);
return;
}
_mgr.processOpenSOCKSTunnel(listenPort, out);
} else if ("openserver".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String serverHost = null;
String serverKeys = null;
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
serverHost = tok.nextToken();
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
serverKeys = tok.nextToken();
_mgr.processOpenServer(serverHost, listenPort, serverKeys, out);
} else {
_mgr.unknownCommand(command, out);
}
}
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
serverKeys = tok.nextToken();
_mgr.processOpenServer(serverHost, listenPort, serverKeys, out);
} else {
_mgr.unknownCommand(command, out);
}
}
}
}
}

View File

@ -26,31 +26,30 @@ public class I2PSOCKSTunnel extends I2PTunnelClientBase {
// I2PSOCKSTunnel(localPort, l, ownDest, (EventDispatcher)null);
//}
public I2PSOCKSTunnel(int localPort, Logging l, boolean ownDest,
EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "SOCKSHandler");
public I2PSOCKSTunnel(int localPort, Logging l, boolean ownDest, EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "SOCKSHandler");
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openSOCKSTunnelResult", "error");
return;
}
setName(getLocalPort() + " -> SOCKSTunnel");
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openSOCKSTunnelResult", "error");
return;
}
startRunning();
setName(getLocalPort() + " -> SOCKSTunnel");
notifyEvent("openSOCKSTunnelResult", "ok");
startRunning();
notifyEvent("openSOCKSTunnelResult", "ok");
}
protected void clientConnectionRun(Socket s) {
try {
SOCKSServer serv = SOCKSServerFactory.createSOCKSServer(s);
Socket clientSock = serv.getClientSocket();
I2PSocket destSock = serv.getDestinationI2PSocket();
new I2PTunnelRunner (clientSock, destSock, sockLock, null);
} catch (SOCKSException e) {
_log.error("Error from SOCKS connection: " + e.getMessage());
closeSocket(s);
}
try {
SOCKSServer serv = SOCKSServerFactory.createSOCKSServer(s);
Socket clientSock = serv.getClientSocket();
I2PSocket destSock = serv.getDestinationI2PSocket();
new I2PTunnelRunner(clientSock, destSock, sockLock, null);
} catch (SOCKSException e) {
_log.error("Error from SOCKS connection: " + e.getMessage());
closeSocket(s);
}
}
}
}

View File

@ -42,189 +42,168 @@ public class SOCKS5Server extends SOCKSServer {
* @param clientSock client socket
*/
public SOCKS5Server(Socket clientSock) {
this.clientSock = clientSock;
this.clientSock = clientSock;
}
public Socket getClientSocket() throws SOCKSException {
setupServer();
setupServer();
return clientSock;
return clientSock;
}
protected void setupServer() throws SOCKSException {
if (setupCompleted) {
return;
}
if (setupCompleted) { return; }
DataInputStream in;
DataOutputStream out;
try {
in = new DataInputStream(clientSock.getInputStream());
out = new DataOutputStream(clientSock.getOutputStream());
DataInputStream in;
DataOutputStream out;
try {
in = new DataInputStream(clientSock.getInputStream());
out = new DataOutputStream(clientSock.getOutputStream());
init(in, out);
manageRequest(in, out);
} catch (IOException e) {
throw new SOCKSException("Connection error ("
+ e.getMessage() + ")");
}
init(in, out);
manageRequest(in, out);
} catch (IOException e) {
throw new SOCKSException("Connection error (" + e.getMessage() + ")");
}
setupCompleted = true;
setupCompleted = true;
}
/**
* 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 {
int nMethods = in.readByte() & 0xff;
boolean methodOk = false;
int method = Method.NO_ACCEPTABLE_METHODS;
private void init(DataInputStream in, DataOutputStream out) throws IOException, SOCKSException {
int nMethods = in.readByte() & 0xff;
boolean methodOk = false;
int method = Method.NO_ACCEPTABLE_METHODS;
for (int i = 0; i < nMethods; ++i) {
method = in.readByte() & 0xff;
if (method == Method.NO_AUTH_REQUIRED) {
// That's fine, we do support this method
break;
}
}
boolean canContinue = false;
switch (method) {
case Method.NO_AUTH_REQUIRED:
_log.debug("no authentication required");
sendInitReply(Method.NO_AUTH_REQUIRED, out);
return;
default:
_log.debug("no suitable authentication methods found ("
+ Integer.toHexString(method)+ ")");
sendInitReply(Method.NO_ACCEPTABLE_METHODS, out);
throw new SOCKSException("Unsupported authentication method");
}
for (int i = 0; i < nMethods; ++i) {
method = in.readByte() & 0xff;
if (method == Method.NO_AUTH_REQUIRED) {
// That's fine, we do support this method
break;
}
}
boolean canContinue = false;
switch (method) {
case Method.NO_AUTH_REQUIRED:
_log.debug("no authentication required");
sendInitReply(Method.NO_AUTH_REQUIRED, out);
return;
default:
_log.debug("no suitable authentication methods found (" + Integer.toHexString(method) + ")");
sendInitReply(Method.NO_ACCEPTABLE_METHODS, out);
throw new SOCKSException("Unsupported authentication method");
}
}
/**
* SOCKS5 request management. This method assumes that all the
* stuff preceding or enveloping the actual request (e.g. protocol
* initialization, integrity/confidentiality encapsulations, etc)
* has been stripped out of the input/output streams.
*/
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?)");
throw new SOCKSException("Invalid protocol version in request");
}
int command = in.readByte() & 0xff;
switch (command) {
case Command.CONNECT:
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);
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);
throw new SOCKSException("UDP ASSOCIATE command not supported");
default:
_log.debug("unknown command in request ("
+ Integer.toHexString(command) + ")");
throw new SOCKSException("Invalid command in request");
}
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?)");
throw new SOCKSException("Invalid protocol version in request");
}
{
// Reserved byte, should be 0x00
byte rsv = in.readByte();
}
int command = in.readByte() & 0xff;
switch (command) {
case Command.CONNECT:
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);
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);
throw new SOCKSException("UDP ASSOCIATE command not supported");
default:
_log.debug("unknown command in request (" + Integer.toHexString(command) + ")");
throw new SOCKSException("Invalid command in request");
}
int addressType = in.readByte() & 0xff;
switch (addressType) {
case AddressType.IPV4:
connHostName = new String("");
for (int i = 0; i < 4; ++i) {
int octet = in.readByte() & 0xff;
connHostName += Integer.toString(octet);
if (i != 3) {
connHostName += ".";
}
}
_log.warn("IPV4 address type in request: " + connHostName
+ ". Is your client secure?");
break;
case AddressType.DOMAINNAME:
{
int addrLen = in.readByte() & 0xff;
if (addrLen == 0) {
_log.debug("0-sized address length? wtf?");
throw new SOCKSException("Illegal DOMAINNAME length");
}
byte addr[] = new byte[addrLen];
in.readFully(addr);
connHostName = new String(addr);
}
_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);
throw new SOCKSException("IPV6 addresses not supported");
default:
_log.debug("unknown address type in request ("
+ Integer.toHexString(command) + ")");
throw new SOCKSException("Invalid addresses type in request");
}
connPort = in.readUnsignedShort();
if (connPort == 0) {
_log.debug("trying to connect to TCP port 0? Dropping!");
throw new SOCKSException("Invalid port number in request");
}
{
// Reserved byte, should be 0x00
byte rsv = in.readByte();
}
int addressType = in.readByte() & 0xff;
switch (addressType) {
case AddressType.IPV4:
connHostName = new String("");
for (int i = 0; i < 4; ++i) {
int octet = in.readByte() & 0xff;
connHostName += Integer.toString(octet);
if (i != 3) {
connHostName += ".";
}
}
_log.warn("IPV4 address type in request: " + connHostName + ". Is your client secure?");
break;
case AddressType.DOMAINNAME:
{
int addrLen = in.readByte() & 0xff;
if (addrLen == 0) {
_log.debug("0-sized address length? wtf?");
throw new SOCKSException("Illegal DOMAINNAME length");
}
byte addr[] = new byte[addrLen];
in.readFully(addr);
connHostName = new String(addr);
}
_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);
throw new SOCKSException("IPV6 addresses not supported");
default:
_log.debug("unknown address type in request (" + Integer.toHexString(command) + ")");
throw new SOCKSException("Invalid addresses type in request");
}
connPort = in.readUnsignedShort();
if (connPort == 0) {
_log.debug("trying to connect to TCP port 0? Dropping!");
throw new SOCKSException("Invalid port number in request");
}
}
protected void confirmConnection() throws SOCKSException {
DataInputStream in;
DataOutputStream out;
try {
out = new DataOutputStream(clientSock.getOutputStream());
sendRequestReply(Reply.SUCCEEDED,
AddressType.IPV4,
InetAddress.getByName("127.0.0.1"),
null, 1, out);
} catch (IOException e) {
throw new SOCKSException("Connection error ("
+ e.getMessage() + ")");
}
DataInputStream in;
DataOutputStream out;
try {
out = new DataOutputStream(clientSock.getOutputStream());
sendRequestReply(Reply.SUCCEEDED, AddressType.IPV4, InetAddress.getByName("127.0.0.1"), null, 1, out);
} catch (IOException e) {
throw new SOCKSException("Connection error (" + e.getMessage() + ")");
}
}
/**
* Send the specified reply during SOCKS5 initialization
*/
private void sendInitReply(int replyCode,
DataOutputStream out) throws IOException {
ByteArrayOutputStream reps = new ByteArrayOutputStream();
private void sendInitReply(int replyCode, DataOutputStream out) throws IOException {
ByteArrayOutputStream reps = new ByteArrayOutputStream();
reps.write(SOCKS_VERSION_5);
reps.write(replyCode);
reps.write(SOCKS_VERSION_5);
reps.write(replyCode);
byte[] reply = reps.toByteArray();
byte[] reply = reps.toByteArray();
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Sending init reply:\n" + HexDump.dump(reply));
}
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Sending init reply:\n" + HexDump.dump(reply));
}
out.write(reply);
out.write(reply);
}
/**
@ -232,78 +211,72 @@ 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 {
ByteArrayOutputStream reps = new ByteArrayOutputStream();
DataOutputStream dreps = new DataOutputStream(reps);
dreps.write(SOCKS_VERSION_5);
dreps.write(replyCode);
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);
// Reserved byte, should be 0x00
dreps.write(0x00);
dreps.write(SOCKS_VERSION_5);
dreps.write(replyCode);
dreps.write(addressType);
switch (addressType) {
case AddressType.IPV4:
dreps.write(inetAddr.getAddress());
break;
case AddressType.DOMAINNAME:
dreps.writeByte(domainName.length());
dreps.writeBytes(domainName);
break;
default:
_log.error("unknown address type passed to sendReply() ("
+ Integer.toHexString(addressType) + ")! wtf?");
return;
}
// Reserved byte, should be 0x00
dreps.write(0x00);
dreps.writeShort(bindPort);
dreps.write(addressType);
byte[] reply = reps.toByteArray();
switch (addressType) {
case AddressType.IPV4:
dreps.write(inetAddr.getAddress());
break;
case AddressType.DOMAINNAME:
dreps.writeByte(domainName.length());
dreps.writeBytes(domainName);
break;
default:
_log.error("unknown address type passed to sendReply() (" + Integer.toHexString(addressType) + ")! wtf?");
return;
}
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Sending request reply:\n" + HexDump.dump(reply));
}
dreps.writeShort(bindPort);
out.write(reply);
byte[] reply = reps.toByteArray();
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Sending request reply:\n" + HexDump.dump(reply));
}
out.write(reply);
}
/*
* Some namespaces to enclose SOCKS protocol codes
*/
private class Method {
private static final int NO_AUTH_REQUIRED = 0x00;
private static final int NO_ACCEPTABLE_METHODS = 0xff;
private static final int NO_AUTH_REQUIRED = 0x00;
private static final int NO_ACCEPTABLE_METHODS = 0xff;
}
private class AddressType {
private static final int IPV4 = 0x01;
private static final int DOMAINNAME = 0x03;
private static final int IPV6 = 0x04;
private static final int IPV4 = 0x01;
private static final int DOMAINNAME = 0x03;
private static final int IPV6 = 0x04;
}
private class Command {
private static final int CONNECT = 0x01;
private static final int BIND = 0x02;
private static final int UDP_ASSOCIATE = 0x03;
private static final int CONNECT = 0x01;
private static final int BIND = 0x02;
private static final int UDP_ASSOCIATE = 0x03;
}
private class Reply {
private static final int SUCCEEDED = 0x00;
private static final int GENERAL_SOCKS_SERVER_FAILURE = 0x01;
private static final int CONNECTION_NOT_ALLOWED_BY_RULESET = 0x02;
private static final int NETWORK_UNREACHABLE = 0x03;
private static final int HOST_UNREACHABLE = 0x04;
private static final int CONNECTION_REFUSED = 0x05;
private static final int TTL_EXPIRED = 0x06;
private static final int COMMAND_NOT_SUPPORTED = 0x07;
private static final int ADDRESS_TYPE_NOT_SUPPORTED = 0x08;
private static final int SUCCEEDED = 0x00;
private static final int GENERAL_SOCKS_SERVER_FAILURE = 0x01;
private static final int CONNECTION_NOT_ALLOWED_BY_RULESET = 0x02;
private static final int NETWORK_UNREACHABLE = 0x03;
private static final int HOST_UNREACHABLE = 0x04;
private static final int CONNECTION_REFUSED = 0x05;
private static final int TTL_EXPIRED = 0x06;
private static final int COMMAND_NOT_SUPPORTED = 0x07;
private static final int ADDRESS_TYPE_NOT_SUPPORTED = 0x08;
}
}
}

View File

@ -14,10 +14,10 @@ package net.i2p.i2ptunnel.socks;
public class SOCKSException extends Exception {
public SOCKSException() {
super();
super();
}
public SOCKSException(String s) {
super(s);
super(s);
}
}
}

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
*/
@ -60,40 +59,39 @@ public abstract class SOCKSServer {
* @return an I2PSocket connected with the destination
*/
public I2PSocket getDestinationI2PSocket() throws SOCKSException {
setupServer();
setupServer();
if (connHostName == null) {
_log.error("BUG: destination host name has not been initialized!");
throw new SOCKSException("BUG! See the logs!");
}
if (connPort == 0) {
_log.error("BUG: destination port has not been initialized!");
throw new SOCKSException("BUG! See the logs!");
}
if (connHostName == null) {
_log.error("BUG: destination host name has not been initialized!");
throw new SOCKSException("BUG! See the logs!");
}
if (connPort == 0) {
_log.error("BUG: destination port has not been initialized!");
throw new SOCKSException("BUG! See the logs!");
}
// FIXME: here we should read our config file, select an
// outproxy, and instantiate the proper socket class that
// handles the outproxy itself (SOCKS4a, SOCKS5, HTTP CONNECT...).
I2PSocket destSock;
// FIXME: here we should read our config file, select an
// outproxy, and instantiate the proper socket class that
// handles the outproxy itself (SOCKS4a, SOCKS5, HTTP CONNECT...).
I2PSocket destSock;
try {
if (connHostName.toLowerCase().endsWith(".i2p")) {
_log.debug("connecting to " + connHostName + "...");
I2PSocketManager sm = I2PSocketManagerFactory.createManager();
destSock = sm.connect(I2PTunnel.destFromName(connHostName),
new I2PSocketOptions());
confirmConnection();
_log.debug("connection confirmed - exchanging data...");
} else {
_log.error("We don't support outproxies (yet)");
throw new SOCKSException("Ouproxies not supported (yet)");
}
} catch (DataFormatException e) {
throw new SOCKSException("Error in destination format");
} catch (I2PException e) {
throw new SOCKSException("I2P error (" + e.getMessage() + ")");
}
return destSock;
try {
if (connHostName.toLowerCase().endsWith(".i2p")) {
_log.debug("connecting to " + connHostName + "...");
I2PSocketManager sm = I2PSocketManagerFactory.createManager();
destSock = sm.connect(I2PTunnel.destFromName(connHostName), new I2PSocketOptions());
confirmConnection();
_log.debug("connection confirmed - exchanging data...");
} else {
_log.error("We don't support outproxies (yet)");
throw new SOCKSException("Ouproxies not supported (yet)");
}
} catch (DataFormatException e) {
throw new SOCKSException("Error in destination format");
} catch (I2PException e) {
throw new SOCKSException("I2P error (" + e.getMessage() + ")");
}
return destSock;
}
}
}

View File

@ -27,27 +27,26 @@ public class SOCKSServerFactory {
* @param s a Socket used to choose the SOCKS server type
*/
public static SOCKSServer createSOCKSServer(Socket s) throws SOCKSException {
SOCKSServer serv;
SOCKSServer serv;
try {
DataInputStream in = new DataInputStream(s.getInputStream());
int socksVer = in.readByte();
switch (socksVer) {
case 0x05: // SOCKS version 5
serv = new SOCKS5Server(s);
break;
default:
_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() + ")");
}
try {
DataInputStream in = new DataInputStream(s.getInputStream());
int socksVer = in.readByte();
return serv;
switch (socksVer) {
case 0x05:
// SOCKS version 5
serv = new SOCKS5Server(s);
break;
default:
_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() + ")");
}
return serv;
}
}
}