format (shendaras)

This commit is contained in:
shendaras
2004-04-10 11:50:11 +00:00
committed by zzz
parent 17a1b11f66
commit 51c49d7c1b
17 changed files with 1462 additions and 1464 deletions

View File

@ -6,8 +6,8 @@ public class ByteCollector {
int size; int size;
public ByteCollector() { public ByteCollector() {
contents=new byte[80]; contents = new byte[80];
size=0; size = 0;
} }
public ByteCollector(byte[] b) { public ByteCollector(byte[] b) {
@ -20,27 +20,27 @@ public class ByteCollector {
append(b); append(b);
} }
public ByteCollector append (byte b) { public ByteCollector append(byte b) {
ensureCapacity(size+1); ensureCapacity(size + 1);
contents[size++]=b; contents[size++] = b;
return this; return this;
} }
public ByteCollector append (byte[] b) { public ByteCollector append(byte[] b) {
ensureCapacity(size+b.length); ensureCapacity(size + b.length);
System.arraycopy(b,0,contents,size,b.length); System.arraycopy(b, 0, contents, size, b.length);
size+=b.length; size += b.length;
return this; return this;
} }
public ByteCollector append(byte[] b, int len) { public ByteCollector append(byte[] b, int len) {
return append(b,0,len); return append(b, 0, len);
} }
public ByteCollector append(byte[] b, int off, int len) { public ByteCollector append(byte[] b, int off, int len) {
ensureCapacity(size+len); ensureCapacity(size + len);
System.arraycopy(b,off,contents,size,len); System.arraycopy(b, off, contents, size, len);
size+=len; size += len;
return this; return this;
} }
@ -50,8 +50,8 @@ public class ByteCollector {
} }
public byte[] toByteArray() { public byte[] toByteArray() {
byte[] result=new byte[size]; byte[] result = new byte[size];
System.arraycopy(contents,0,result,0,size); System.arraycopy(contents, 0, result, 0, size);
return result; return result;
} }
@ -62,9 +62,9 @@ public class ByteCollector {
return res; return res;
} else { } else {
byte[] result = new byte[maxlen]; byte[] result = new byte[maxlen];
System.arraycopy(contents,0,result,0,maxlen); System.arraycopy(contents, 0, result, 0, maxlen);
System.arraycopy(contents,maxlen,contents,0,size-maxlen); System.arraycopy(contents, maxlen, contents, 0, size - maxlen);
size-=maxlen; size -= maxlen;
return result; return result;
} }
} }
@ -74,21 +74,21 @@ public class ByteCollector {
} }
public boolean ensureCapacity(int cap) { public boolean ensureCapacity(int cap) {
if (contents.length<cap) { if (contents.length < cap) {
int l=contents.length; int l = contents.length;
while (l<cap) { while (l < cap) {
l=(l*3)/2+1; l = (l * 3) / 2 + 1;
} }
byte[] newcont=new byte[l]; byte[] newcont = new byte[l];
System.arraycopy(contents,0,newcont,0,size); System.arraycopy(contents, 0, newcont, 0, size);
contents=newcont; contents = newcont;
return true; return true;
} }
return false; return false;
} }
public boolean isEmpty() { public boolean isEmpty() {
return size==0; return size == 0;
} }
public int indexOf(ByteCollector bc) { public int indexOf(ByteCollector bc) {
@ -98,14 +98,13 @@ public class ByteCollector {
public int indexOf(byte b) { public int indexOf(byte b) {
// optimieren? // optimieren?
return indexOf(new byte[] {b}); return indexOf(new byte[] { b});
} }
public int indexOf(byte[] ba) { public int indexOf(byte[] ba) {
loop: loop: for (int i = 0; i < size - ba.length + 1; i++) {
for (int i=0;i<size-ba.length+1;i++) { for (int j = 0; j < ba.length; j++) {
for (int j=0;j<ba.length;j++) { if (contents[i + j] != ba[j]) continue loop;
if (contents[i+j]!=ba[j]) continue loop;
} }
return i; return i;
} }
@ -113,12 +112,12 @@ public class ByteCollector {
} }
public void clear() { public void clear() {
size=0; size = 0;
} }
public void clearAndShorten() { public void clearAndShorten() {
size=0; size = 0;
contents=new byte[80]; contents = new byte[80];
} }
public String toString() { public String toString() {
@ -126,19 +125,19 @@ public class ByteCollector {
} }
public int hashCode() { public int hashCode() {
int h =0; int h = 0;
for (int i=0;i<size;i++) { for (int i = 0; i < size; i++) {
h+=contents[i]*contents[i]; h += contents[i] * contents[i];
} }
return h; return h;
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (o instanceof ByteCollector) { if (o instanceof ByteCollector) {
ByteCollector by=(ByteCollector)o; ByteCollector by = (ByteCollector) o;
if (size!=by.size) return false; if (size != by.size) return false;
for (int i=0;i<size;i++) { for (int i = 0; i < size; i++) {
if (contents[i]!=by.contents[i]) return false; if (contents[i] != by.contents[i]) return false;
} }
return true; return true;
} else { } else {
@ -147,13 +146,12 @@ public class ByteCollector {
} }
public byte removeFirst() { public byte removeFirst() {
byte bb=contents[0]; byte bb = contents[0];
if (size==0) if (size == 0) throw new IllegalArgumentException("ByteCollector is empty");
throw new IllegalArgumentException("ByteCollector is empty"); if (size > 1)
if(size>1) System.arraycopy(contents, 1, contents, 0, --size);
System.arraycopy(contents,1,contents,0,--size);
else else
size=0; size = 0;
return bb; return bb;
} }
} }

View File

@ -10,28 +10,28 @@ import net.i2p.util.Log;
class I2PServerSocketImpl implements I2PServerSocket { class I2PServerSocketImpl implements I2PServerSocket {
private final static Log _log = new Log(I2PServerSocketImpl.class); private final static Log _log = new Log(I2PServerSocketImpl.class);
private I2PSocketManager mgr; private I2PSocketManager mgr;
private I2PSocket cached=null; // buffer one socket here private I2PSocket cached = null; // buffer one socket here
public I2PServerSocketImpl(I2PSocketManager mgr) { public I2PServerSocketImpl(I2PSocketManager mgr) {
this.mgr = mgr; this.mgr = mgr;
} }
public synchronized I2PSocket accept() throws I2PException { public synchronized I2PSocket accept() throws I2PException {
while(cached == null) { while (cached == null) {
myWait(); myWait();
} }
I2PSocket ret=cached; I2PSocket ret = cached;
cached=null; cached = null;
notifyAll(); notifyAll();
_log.debug("TIMING: handed out accept result "+ret.hashCode()); _log.debug("TIMING: handed out accept result " + ret.hashCode());
return ret; return ret;
} }
public synchronized boolean getNewSocket(I2PSocket s){ public synchronized boolean getNewSocket(I2PSocket s) {
while(cached != null) { while (cached != null) {
myWait(); myWait();
} }
cached=s; cached = s;
notifyAll(); notifyAll();
return true; return true;
} }
@ -41,10 +41,13 @@ class I2PServerSocketImpl implements I2PServerSocket {
} }
private void myWait() { private void myWait() {
try{ try {
wait(); wait();
} catch (InterruptedException ex) {} } catch (InterruptedException ex) {
}
} }
public I2PSocketManager getManager() { return mgr; } public I2PSocketManager getManager() {
return mgr;
}
} }

View File

@ -18,8 +18,8 @@ import net.i2p.util.Log;
class I2PSocketImpl implements I2PSocket { class I2PSocketImpl implements I2PSocket {
private final static Log _log = new Log(I2PSocketImpl.class); private final static Log _log = new Log(I2PSocketImpl.class);
public static final int MAX_PACKET_SIZE = 1024*32; public static final int MAX_PACKET_SIZE = 1024 * 32;
public static final int PACKET_DELAY=100; public static final int PACKET_DELAY = 100;
private I2PSocketManager manager; private I2PSocketManager manager;
private Destination local; private Destination local;
@ -31,11 +31,10 @@ class I2PSocketImpl implements I2PSocket {
private I2POutputStream out; private I2POutputStream out;
private boolean outgoing; private boolean outgoing;
private Object flagLock = new Object(); private Object flagLock = new Object();
private boolean closed = false, sendClose=true, closed2=false; private boolean closed = false, sendClose = true, closed2 = false;
public I2PSocketImpl(Destination peer, I2PSocketManager mgr, public I2PSocketImpl(Destination peer, I2PSocketManager mgr, boolean outgoing, String localID) {
boolean outgoing, String localID) { this.outgoing = outgoing;
this.outgoing=outgoing;
manager = mgr; manager = mgr;
remote = peer; remote = peer;
local = mgr.getSession().getMyDestination(); local = mgr.getSession().getMyDestination();
@ -51,8 +50,8 @@ class I2PSocketImpl implements I2PSocket {
} }
public void setRemoteID(String id) { public void setRemoteID(String id) {
synchronized(remoteIDWaiter) { synchronized (remoteIDWaiter) {
remoteID=id; remoteID = id;
remoteIDWaiter.notifyAll(); remoteIDWaiter.notifyAll();
} }
} }
@ -60,22 +59,25 @@ class I2PSocketImpl implements I2PSocket {
public String getRemoteID(boolean wait) throws InterruptedIOException { public String getRemoteID(boolean wait) throws InterruptedIOException {
return getRemoteID(wait, -1); return getRemoteID(wait, -1);
} }
public String getRemoteID(boolean wait, long maxWait) throws InterruptedIOException { public String getRemoteID(boolean wait, long maxWait) throws InterruptedIOException {
long dieAfter = System.currentTimeMillis() + maxWait; long dieAfter = System.currentTimeMillis() + maxWait;
synchronized(remoteIDWaiter) { synchronized (remoteIDWaiter) {
while (wait && remoteID==null) { while (wait && remoteID == null) {
try { try {
if (maxWait > 0) if (maxWait > 0)
remoteIDWaiter.wait(maxWait); remoteIDWaiter.wait(maxWait);
else else
remoteIDWaiter.wait(); remoteIDWaiter.wait();
} catch (InterruptedException ex) {} } catch (InterruptedException ex) {
}
if ( (maxWait > 0) && (System.currentTimeMillis() > dieAfter) ) if ((maxWait > 0) && (System.currentTimeMillis() > dieAfter))
throw new InterruptedIOException("Timed out waiting for remote ID"); throw new InterruptedIOException("Timed out waiting for remote ID");
} }
if (wait) { if (wait) {
_log.debug("TIMING: RemoteID set to " + I2PSocketManager.getReadableForm(remoteID) +" for "+this.hashCode()); _log.debug("TIMING: RemoteID set to " + I2PSocketManager.getReadableForm(remoteID) + " for "
+ this.hashCode());
} }
return remoteID; return remoteID;
} }
@ -92,19 +94,22 @@ class I2PSocketImpl implements I2PSocket {
/** /**
* Return the Destination of this side of the socket. * Return the Destination of this side of the socket.
*/ */
public Destination getThisDestination() { return local; } public Destination getThisDestination() {
return local;
}
/** /**
* Return the destination of the peer. * Return the destination of the peer.
*/ */
public Destination getPeerDestination() { return remote; } public Destination getPeerDestination() {
return remote;
}
/** /**
* Return an InputStream to read from the socket. * Return an InputStream to read from the socket.
*/ */
public InputStream getInputStream() throws IOException { public InputStream getInputStream() throws IOException {
if ( (in == null) ) if ((in == null)) throw new IOException("Not connected");
throw new IOException("Not connected");
return in; return in;
} }
@ -112,8 +117,7 @@ class I2PSocketImpl implements I2PSocket {
* Return an OutputStream to write into the socket. * Return an OutputStream to write into the socket.
*/ */
public OutputStream getOutputStream() throws IOException { public OutputStream getOutputStream() throws IOException {
if ( (out == null) ) if ((out == null)) throw new IOException("Not connected");
throw new IOException("Not connected");
return out; return out;
} }
@ -121,27 +125,26 @@ class I2PSocketImpl implements I2PSocket {
* Closes the socket if not closed yet * Closes the socket if not closed yet
*/ */
public void close() throws IOException { public void close() throws IOException {
synchronized(flagLock) { synchronized (flagLock) {
_log.debug("Closing connection"); _log.debug("Closing connection");
closed=true; closed = true;
} }
out.close(); out.close();
in.notifyClosed(); in.notifyClosed();
} }
public void internalClose() { public void internalClose() {
synchronized(flagLock) { synchronized (flagLock) {
closed=true; closed = true;
closed2=true; closed2 = true;
sendClose=false; sendClose = false;
} }
out.close(); out.close();
in.notifyClosed(); in.notifyClosed();
} }
private byte getMask(int add) { private byte getMask(int add) {
return (byte)((outgoing?(byte)0xA0:(byte)0x50)+(byte)add); return (byte) ((outgoing ? (byte) 0xA0 : (byte) 0x50) + (byte) add);
} }
//-------------------------------------------------- //--------------------------------------------------
@ -158,27 +161,27 @@ class I2PSocketImpl implements I2PSocket {
} }
public synchronized int read(byte[] b, int off, int len) throws IOException { public synchronized int read(byte[] b, int off, int len) throws IOException {
_log.debug("Read called: "+this.hashCode()); _log.debug("Read called: " + this.hashCode());
if (len==0) return 0; if (len == 0) return 0;
byte[] read = bc.startToByteArray(len); byte[] read = bc.startToByteArray(len);
while (read.length==0) { while (read.length == 0) {
synchronized(flagLock) { synchronized (flagLock) {
if (closed){ if (closed) {
_log.debug("Closed is set, so closing stream: "+this.hashCode()); _log.debug("Closed is set, so closing stream: " + this.hashCode());
return -1; return -1;
} }
} }
try { try {
wait(); wait();
} catch (InterruptedException ex) {} } catch (InterruptedException ex) {
}
read = bc.startToByteArray(len); read = bc.startToByteArray(len);
} }
if (read.length>len) throw new RuntimeException("BUG"); if (read.length > len) throw new RuntimeException("BUG");
System.arraycopy(read,0,b,off,read.length); System.arraycopy(read, 0, b, off, read.length);
if (_log.shouldLog(Log.DEBUG)) { if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Read from I2PInputStream " + this.hashCode() _log.debug("Read from I2PInputStream " + this.hashCode() + " returned " + read.length + " bytes");
+ " returned "+read.length+" bytes");
} }
//if (_log.shouldLog(Log.DEBUG)) { //if (_log.shouldLog(Log.DEBUG)) {
// _log.debug("Read from I2PInputStream " + this.hashCode() // _log.debug("Read from I2PInputStream " + this.hashCode()
@ -193,11 +196,11 @@ class I2PSocketImpl implements I2PSocket {
} }
public void queueData(byte[] data) { public void queueData(byte[] data) {
queueData(data,0,data.length); queueData(data, 0, data.length);
} }
public synchronized void queueData(byte[] data, int off, int len) { public synchronized void queueData(byte[] data, int off, int len) {
_log.debug("Insert "+len+" bytes into queue: "+this.hashCode()); _log.debug("Insert " + len + " bytes into queue: " + this.hashCode());
bc.append(data, off, len); bc.append(data, off, len);
notifyAll(); notifyAll();
} }
@ -213,14 +216,15 @@ class I2PSocketImpl implements I2PSocket {
public I2PInputStream sendTo; public I2PInputStream sendTo;
public I2POutputStream(I2PInputStream sendTo) { public I2POutputStream(I2PInputStream sendTo) {
this.sendTo=sendTo; this.sendTo = sendTo;
}
public void write(int b) throws IOException {
write(new byte[] {(byte)b});
} }
public void write (byte[] b, int off, int len) throws IOException { public void write(int b) throws IOException {
sendTo.queueData(b,off,len); write(new byte[] { (byte) b});
}
public void write(byte[] b, int off, int len) throws IOException {
sendTo.queueData(b, off, len);
} }
public void close() { public void close() {
@ -233,8 +237,8 @@ class I2PSocketImpl implements I2PSocket {
public InputStream in; public InputStream in;
public I2PSocketRunner(InputStream in) { public I2PSocketRunner(InputStream in) {
_log.debug("Runner's input stream is: "+in.hashCode()); _log.debug("Runner's input stream is: " + in.hashCode());
this.in=in; this.in = in;
setName("SocketRunner from " + I2PSocketImpl.this.remote.calculateHash().toBase64().substring(0, 4)); setName("SocketRunner from " + I2PSocketImpl.this.remote.calculateHash().toBase64().substring(0, 4));
start(); start();
} }
@ -245,18 +249,17 @@ class I2PSocketImpl implements I2PSocket {
boolean sent = true; boolean sent = true;
try { try {
int len, bcsize; int len, bcsize;
// try { // try {
while (true) { while (true) {
len = in.read(buffer); len = in.read(buffer);
bcsize = bc.getCurrentSize(); bcsize = bc.getCurrentSize();
if (len != -1) { if (len != -1) {
bc.append(buffer,len); bc.append(buffer, len);
} else if (bcsize == 0) { } else if (bcsize == 0) {
break; break;
} }
if ((bcsize < MAX_PACKET_SIZE) if ((bcsize < MAX_PACKET_SIZE) && (in.available() == 0)) {
&& (in.available()==0)) { _log.debug("Runner Point d: " + this.hashCode());
_log.debug("Runner Point d: "+this.hashCode());
try { try {
Thread.sleep(PACKET_DELAY); Thread.sleep(PACKET_DELAY);
@ -264,11 +267,10 @@ class I2PSocketImpl implements I2PSocket {
e.printStackTrace(); e.printStackTrace();
} }
} }
if ((bcsize >= MAX_PACKET_SIZE) if ((bcsize >= MAX_PACKET_SIZE) || (in.available() == 0)) {
|| (in.available()==0) ) {
byte[] data = bc.startToByteArray(MAX_PACKET_SIZE); byte[] data = bc.startToByteArray(MAX_PACKET_SIZE);
if (data.length > 0) { if (data.length > 0) {
_log.debug("Message size is: "+data.length); _log.debug("Message size is: " + data.length);
sent = sendBlock(data); sent = sendBlock(data);
if (!sent) { if (!sent) {
_log.error("Error sending message to peer. Killing socket runner"); _log.error("Error sending message to peer. Killing socket runner");
@ -278,26 +280,24 @@ class I2PSocketImpl implements I2PSocket {
} }
} }
if ((bc.getCurrentSize() > 0) && sent) { if ((bc.getCurrentSize() > 0) && sent) {
_log.error("A SCARY MONSTER HAS EATEN SOME DATA! " _log.error("A SCARY MONSTER HAS EATEN SOME DATA! " + "(input stream: " + in.hashCode() + "; "
+ "(input stream: " + in.hashCode() + "; "
+ "queue size: " + bc.getCurrentSize() + ")"); + "queue size: " + bc.getCurrentSize() + ")");
} }
synchronized(flagLock) { synchronized (flagLock) {
closed2=true; closed2 = true;
} }
// } catch (IOException ex) { // } catch (IOException ex) {
// if (_log.shouldLog(Log.INFO)) // if (_log.shouldLog(Log.INFO))
// _log.info("Error reading and writing", ex); // _log.info("Error reading and writing", ex);
// } // }
boolean sc; boolean sc;
synchronized(flagLock) { synchronized (flagLock) {
sc=sendClose; sc = sendClose;
} // FIXME: Race here? } // FIXME: Race here?
if (sc) { if (sc) {
_log.info("Sending close packet: "+outgoing); _log.info("Sending close packet: " + outgoing);
byte[] packet = I2PSocketManager.makePacket byte[] packet = I2PSocketManager.makePacket((byte) (getMask(0x02)), remoteID, new byte[0]);
((byte)(getMask(0x02)),remoteID, new byte[0]); synchronized (manager.getSession()) {
synchronized(manager.getSession()) {
sent = manager.getSession().sendMessage(remote, packet); sent = manager.getSession().sendMessage(remote, packet);
} }
if (!sent) { if (!sent) {
@ -312,23 +312,22 @@ class I2PSocketImpl implements I2PSocket {
// etc.) will get hanged by me personally -- mihi // etc.) will get hanged by me personally -- mihi
_log.error("Error running - **INCONSISTENT STATE!!!**", ex); _log.error("Error running - **INCONSISTENT STATE!!!**", ex);
} catch (I2PException ex) { } catch (I2PException ex) {
_log.error("Error running - **INCONSISTENT STATE!!!**" , ex); _log.error("Error running - **INCONSISTENT STATE!!!**", ex);
} }
} }
private boolean sendBlock(byte data[]) throws I2PSessionException { private boolean sendBlock(byte data[]) throws I2PSessionException {
_log.debug("TIMING: Block to send for "+I2PSocketImpl.this.hashCode()); _log.debug("TIMING: Block to send for " + I2PSocketImpl.this.hashCode());
if (remoteID==null) { if (remoteID == null) {
_log.error("NULL REMOTEID"); _log.error("NULL REMOTEID");
return false; return false;
} }
byte[] packet = I2PSocketManager.makePacket(getMask(0x00), remoteID, byte[] packet = I2PSocketManager.makePacket(getMask(0x00), remoteID, data);
data);
boolean sent; boolean sent;
synchronized(flagLock) { synchronized (flagLock) {
if (closed2) return false; if (closed2) return false;
} }
synchronized(manager.getSession()) { synchronized (manager.getSession()) {
sent = manager.getSession().sendMessage(remote, packet); sent = manager.getSession().sendMessage(remote, packet);
} }
return sent; return sent;

View File

@ -37,11 +37,10 @@ public class I2PSocketManager implements I2PSessionListener {
private HashMap _inSockets; private HashMap _inSockets;
private I2PSocketOptions _defaultOptions; private I2PSocketOptions _defaultOptions;
public static final int PUBKEY_LENGTH=387; public static final int PUBKEY_LENGTH = 387;
public I2PSocketManager() { public I2PSocketManager() {
_session=null; _session = null;
_serverSocket = new I2PServerSocketImpl(this); _serverSocket = new I2PServerSocketImpl(this);
_inSockets = new HashMap(16); _inSockets = new HashMap(16);
_outSockets = new HashMap(16); _outSockets = new HashMap(16);
@ -53,8 +52,7 @@ public class I2PSocketManager implements I2PSessionListener {
public void setSession(I2PSession session) { public void setSession(I2PSession session) {
_session = session; _session = session;
if (session != null) if (session != null) session.setSessionListener(this);
session.setSessionListener(this);
} }
public void disconnected(I2PSession session) { public void disconnected(I2PSession session) {
@ -73,29 +71,27 @@ public class I2PSocketManager implements I2PSessionListener {
_log.debug("Ping received"); _log.debug("Ping received");
return; return;
} }
if (msg.length <4) { if (msg.length < 4) {
_log.error("==== packet too short ===="); _log.error("==== packet too short ====");
return; return;
} }
int type = msg[0] & 0xff; int type = msg[0] & 0xff;
String id = new String(new byte[] {msg[1], msg[2], msg[3]}, String id = new String(new byte[] { msg[1], msg[2], msg[3]}, "ISO-8859-1");
"ISO-8859-1"); byte[] payload = new byte[msg.length - 4];
byte[] payload = new byte[msg.length-4];
System.arraycopy(msg, 4, payload, 0, payload.length); System.arraycopy(msg, 4, payload, 0, payload.length);
_log.debug("Message read: type = [" + Integer.toHexString(type) + _log.debug("Message read: type = [" + Integer.toHexString(type) + "] id = [" + getReadableForm(id)
"] id = [" + getReadableForm(id)+ + "] payload length: " + payload.length + "]");
"] payload length: " + payload.length + "]"); synchronized (lock) {
synchronized(lock) { switch (type) {
switch(type) { case 0x51:
case 0x51: // ACK outgoing // ACK outgoing
s = (I2PSocketImpl) _outSockets.get(id); s = (I2PSocketImpl) _outSockets.get(id);
if (s == null) { if (s == null) {
_log.warn("No socket responsible for ACK packet"); _log.warn("No socket responsible for ACK packet");
return; return;
} }
if (payload.length==3 && s.getRemoteID(false)==null) { if (payload.length == 3 && s.getRemoteID(false) == null) {
String newID = new String(payload, String newID = new String(payload, "ISO-8859-1");
"ISO-8859-1");
s.setRemoteID(newID); s.setRemoteID(newID);
return; return;
} else { } else {
@ -105,23 +101,24 @@ public class I2PSocketManager implements I2PSessionListener {
_log.warn("Remote ID already exists? " + s.getRemoteID()); _log.warn("Remote ID already exists? " + s.getRemoteID());
return; return;
} }
case 0x52: // disconnect outgoing case 0x52:
// disconnect outgoing
_log.debug("*Disconnect outgoing!"); _log.debug("*Disconnect outgoing!");
try { try {
s = (I2PSocketImpl) _outSockets.get(id); s = (I2PSocketImpl) _outSockets.get(id);
if (payload.length==0 && s != null) { if (payload.length == 0 && s != null) {
s.internalClose(); s.internalClose();
_outSockets.remove(id); _outSockets.remove(id);
return; return;
} else { } else {
if (payload.length > 0) if (payload.length > 0) _log.warn("Disconnect packet had " + payload.length + " bytes");
_log.warn("Disconnect packet had " + payload.length + " bytes");
return; return;
} }
} catch (Exception t) { } catch (Exception t) {
_log.error("Ignoring error on disconnect", t); _log.error("Ignoring error on disconnect", t);
} }
case 0x50: // packet send outgoing case 0x50:
// packet send outgoing
_log.debug("*Packet send outgoing [" + payload.length + "]"); _log.debug("*Packet send outgoing [" + payload.length + "]");
s = (I2PSocketImpl) _outSockets.get(id); s = (I2PSocketImpl) _outSockets.get(id);
if (s != null) { if (s != null) {
@ -131,36 +128,31 @@ public class I2PSocketManager implements I2PSessionListener {
_log.error("Null socket with data available"); _log.error("Null socket with data available");
throw new IllegalStateException("Null socket with data available"); throw new IllegalStateException("Null socket with data available");
} }
case 0xA1: // SYN incoming case 0xA1:
// SYN incoming
_log.debug("*Syn!"); _log.debug("*Syn!");
if (payload.length==PUBKEY_LENGTH) { if (payload.length == PUBKEY_LENGTH) {
String newLocalID = makeID(_inSockets); String newLocalID = makeID(_inSockets);
Destination d = new Destination(); Destination d = new Destination();
d.readBytes(new ByteArrayInputStream(payload)); d.readBytes(new ByteArrayInputStream(payload));
s = new I2PSocketImpl(d, this, false, s = new I2PSocketImpl(d, this, false, newLocalID);
newLocalID);
s.setRemoteID(id); s.setRemoteID(id);
if (_serverSocket.getNewSocket(s)) { if (_serverSocket.getNewSocket(s)) {
_inSockets.put(newLocalID, s); _inSockets.put(newLocalID, s);
byte[] packet = makePacket byte[] packet = makePacket((byte) 0x51, id, newLocalID.getBytes("ISO-8859-1"));
((byte)0x51, id,
newLocalID.getBytes("ISO-8859-1"));
boolean replySentOk = false; boolean replySentOk = false;
synchronized(_session) { synchronized (_session) {
replySentOk = _session.sendMessage(d, packet); replySentOk = _session.sendMessage(d, packet);
} }
if (!replySentOk) { if (!replySentOk) {
_log.error("Error sending reply to " + _log.error("Error sending reply to " + d.calculateHash().toBase64()
d.calculateHash().toBase64() + + " in response to a new con message", new Exception("Failed creation"));
" in response to a new con message",
new Exception("Failed creation"));
s.internalClose(); s.internalClose();
} }
} else { } else {
byte[] packet = byte[] packet = (" " + id).getBytes("ISO-8859-1");
(" "+id).getBytes("ISO-8859-1"); packet[0] = 0x52;
packet[0]=0x52;
boolean nackSent = session.sendMessage(d, packet); boolean nackSent = session.sendMessage(d, packet);
if (!nackSent) { if (!nackSent) {
_log.error("Error sending NACK for session creation"); _log.error("Error sending NACK for session creation");
@ -169,27 +161,29 @@ public class I2PSocketManager implements I2PSessionListener {
} }
return; return;
} else { } else {
_log.error("Syn packet that has a payload not equal to the pubkey length (" + payload.length + " != " + PUBKEY_LENGTH + ")"); _log.error("Syn packet that has a payload not equal to the pubkey length (" + payload.length
+ " != " + PUBKEY_LENGTH + ")");
return; return;
} }
case 0xA2: // disconnect incoming case 0xA2:
// disconnect incoming
_log.debug("*Disconnect incoming!"); _log.debug("*Disconnect incoming!");
try { try {
s = (I2PSocketImpl) _inSockets.get(id); s = (I2PSocketImpl) _inSockets.get(id);
if (payload.length==0 && s != null) { if (payload.length == 0 && s != null) {
s.internalClose(); s.internalClose();
_inSockets.remove(id); _inSockets.remove(id);
return; return;
} else { } else {
if (payload.length > 0) if (payload.length > 0) _log.warn("Disconnect packet had " + payload.length + " bytes");
_log.warn("Disconnect packet had " + payload.length + " bytes");
return; return;
} }
} catch (Exception t) { } catch (Exception t) {
_log.error("Ignoring error on disconnect", t); _log.error("Ignoring error on disconnect", t);
return; return;
} }
case 0xA0: // packet send incoming case 0xA0:
// packet send incoming
_log.debug("*Packet send incoming [" + payload.length + "]"); _log.debug("*Packet send incoming [" + payload.length + "]");
s = (I2PSocketImpl) _inSockets.get(id); s = (I2PSocketImpl) _inSockets.get(id);
if (s != null) { if (s != null) {
@ -199,15 +193,13 @@ public class I2PSocketManager implements I2PSessionListener {
_log.error("Null socket with data available"); _log.error("Null socket with data available");
throw new IllegalStateException("Null socket with data available"); throw new IllegalStateException("Null socket with data available");
} }
case 0xFF: // ignore case 0xFF:
// ignore
return; return;
} }
_log.error("\n\n=============== Unknown packet! "+ _log.error("\n\n=============== Unknown packet! " + "============" + "\nType: " + (int) type
"============"+ + "\nID: " + getReadableForm(id) + "\nBase64'ed Data: " + Base64.encode(payload)
"\nType: "+(int)type+ + "\n\n\n");
"\nID: " + getReadableForm(id)+
"\nBase64'ed Data: "+Base64.encode(payload)+
"\n\n\n");
if (id != null) { if (id != null) {
_inSockets.remove(id); _inSockets.remove(id);
_outSockets.remove(id); _outSockets.remove(id);
@ -226,11 +218,17 @@ public class I2PSocketManager implements I2PSessionListener {
_log.error("Abuse reported [" + severity + "]"); _log.error("Abuse reported [" + severity + "]");
} }
public void setDefaultOptions(I2PSocketOptions options) { _defaultOptions = options; } public void setDefaultOptions(I2PSocketOptions options) {
_defaultOptions = options;
}
public I2PSocketOptions getDefaultOptions() { return _defaultOptions ; } public I2PSocketOptions getDefaultOptions() {
return _defaultOptions;
}
public I2PServerSocket getServerSocket() { return _serverSocket; } public I2PServerSocket getServerSocket() {
return _serverSocket;
}
/** /**
* Create a new connected socket (block until the socket is created) * Create a new connected socket (block until the socket is created)
@ -241,50 +239,47 @@ public class I2PSocketManager implements I2PSessionListener {
String localID, lcID; String localID, lcID;
I2PSocketImpl s; I2PSocketImpl s;
synchronized(lock) { synchronized (lock) {
localID=makeID(_outSockets); localID = makeID(_outSockets);
lcID=getReadableForm(localID); lcID = getReadableForm(localID);
s = new I2PSocketImpl(peer, this, true, localID); s = new I2PSocketImpl(peer, this, true, localID);
_outSockets.put(s.getLocalID(),s); _outSockets.put(s.getLocalID(), s);
} }
try { try {
ByteArrayOutputStream pubkey = new ByteArrayOutputStream(); ByteArrayOutputStream pubkey = new ByteArrayOutputStream();
_session.getMyDestination().writeBytes(pubkey); _session.getMyDestination().writeBytes(pubkey);
String remoteID; String remoteID;
byte[] packet = makePacket((byte)0xA1, localID, byte[] packet = makePacket((byte) 0xA1, localID, pubkey.toByteArray());
pubkey.toByteArray());
boolean sent = false; boolean sent = false;
synchronized(_session) { synchronized (_session) {
sent = _session.sendMessage(peer, packet); sent = _session.sendMessage(peer, packet);
} }
if (!sent) { if (!sent) {
_log.info("Unable to send & receive ack for SYN packet"); _log.info("Unable to send & receive ack for SYN packet");
synchronized(lock) { synchronized (lock) {
_outSockets.remove(s.getLocalID()); _outSockets.remove(s.getLocalID());
} }
throw new I2PException("Unable to reach peer"); throw new I2PException("Unable to reach peer");
} }
remoteID = s.getRemoteID(true, options.getConnectTimeout()); remoteID = s.getRemoteID(true, options.getConnectTimeout());
if ("".equals(remoteID)) { if ("".equals(remoteID)) { throw new I2PException("Unable to reach peer"); }
throw new I2PException("Unable to reach peer"); _log.debug("TIMING: s given out for remoteID " + getReadableForm(remoteID));
}
_log.debug("TIMING: s given out for remoteID "+getReadableForm(remoteID));
return s; return s;
} catch (InterruptedIOException ioe) { } catch (InterruptedIOException ioe) {
_log.error("Timeout waiting for ack from syn for id " + getReadableForm(lcID), ioe); _log.error("Timeout waiting for ack from syn for id " + getReadableForm(lcID), ioe);
synchronized(lock) { synchronized (lock) {
_outSockets.remove(s.getLocalID()); _outSockets.remove(s.getLocalID());
} }
throw new I2PException("Timeout waiting for ack"); throw new I2PException("Timeout waiting for ack");
} catch (IOException ex) { } catch (IOException ex) {
_log.error("Error sending syn on id " + getReadableForm(lcID), ex); _log.error("Error sending syn on id " + getReadableForm(lcID), ex);
synchronized(lock) { synchronized (lock) {
_outSockets.remove(s.getLocalID()); _outSockets.remove(s.getLocalID());
} }
throw new I2PException("IOException occurred"); throw new I2PException("IOException occurred");
} catch (I2PException ex) { } catch (I2PException ex) {
_log.info("Error sending syn on id " + getReadableForm(lcID), ex); _log.info("Error sending syn on id " + getReadableForm(lcID), ex);
synchronized(lock) { synchronized (lock) {
_outSockets.remove(s.getLocalID()); _outSockets.remove(s.getLocalID());
} }
throw ex; throw ex;
@ -315,15 +310,15 @@ public class I2PSocketManager implements I2PSessionListener {
*/ */
public boolean ping(Destination peer, long timeoutMs) { public boolean ping(Destination peer, long timeoutMs) {
try { try {
return _session.sendMessage(peer, new byte[] {(byte)0xFF}); return _session.sendMessage(peer, new byte[] { (byte) 0xFF});
} catch (I2PException ex) { } catch (I2PException ex) {
_log.error("I2PException:",ex); _log.error("I2PException:", ex);
return false; return false;
} }
} }
public void removeSocket(I2PSocketImpl sock) { public void removeSocket(I2PSocketImpl sock) {
synchronized(lock) { synchronized (lock) {
_inSockets.remove(sock.getLocalID()); _inSockets.remove(sock.getLocalID());
_outSockets.remove(sock.getLocalID()); _outSockets.remove(sock.getLocalID());
} }
@ -348,11 +343,11 @@ public class I2PSocketManager implements I2PSessionListener {
String newID; String newID;
try { try {
do { do {
int id = (int)(Math.random()*16777215+1); int id = (int) (Math.random() * 16777215 + 1);
byte[] nid = new byte[3]; byte[] nid = new byte[3];
nid[0]=(byte)(id / 65536); nid[0] = (byte) (id / 65536);
nid[1] = (byte)((id/256) % 256); nid[1] = (byte) ((id / 256) % 256);
nid[2]= (byte)(id %256); nid[2] = (byte) (id % 256);
newID = new String(nid, "ISO-8859-1"); newID = new String(nid, "ISO-8859-1");
} while (uniqueIn.get(newID) != null); } while (uniqueIn.get(newID) != null);
return newID; return newID;
@ -368,18 +363,15 @@ public class I2PSocketManager implements I2PSessionListener {
*/ */
public static byte[] makePacket(byte type, String id, byte[] payload) { public static byte[] makePacket(byte type, String id, byte[] payload) {
try { try {
byte[] packet = new byte[payload.length+4]; byte[] packet = new byte[payload.length + 4];
packet[0]=type; packet[0] = type;
byte[] temp = id.getBytes("ISO-8859-1"); byte[] temp = id.getBytes("ISO-8859-1");
if (temp.length != 3) if (temp.length != 3) throw new RuntimeException("Incorrect ID length: " + temp.length);
throw new RuntimeException("Incorrect ID length: "+ System.arraycopy(temp, 0, packet, 1, 3);
temp.length); System.arraycopy(payload, 0, packet, 4, payload.length);
System.arraycopy(temp,0,packet,1,3);
System.arraycopy(payload,0,packet,4,payload.length);
return packet; return packet;
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
if (_log.shouldLog(Log.ERROR)) if (_log.shouldLog(Log.ERROR)) _log.error("Error building the packet", ex);
_log.error("Error building the packet", ex);
return new byte[0]; return new byte[0];
} }
} }

View File

@ -62,11 +62,12 @@ public class I2PSocketManagerFactory {
* *
* @return the newly created socket manager, or null if there were errors * @return the newly created socket manager, or null if there were errors
*/ */
public static I2PSocketManager createManager(InputStream myPrivateKeyStream, String i2cpHost, int i2cpPort, Properties opts) { public static I2PSocketManager createManager(InputStream myPrivateKeyStream, String i2cpHost, int i2cpPort,
Properties opts) {
I2PClient client = I2PClientFactory.createClient(); I2PClient client = I2PClientFactory.createClient();
opts.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_GUARANTEED); opts.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_GUARANTEED);
opts.setProperty(I2PClient.PROP_TCP_HOST, i2cpHost); opts.setProperty(I2PClient.PROP_TCP_HOST, i2cpHost);
opts.setProperty(I2PClient.PROP_TCP_PORT, ""+i2cpPort); opts.setProperty(I2PClient.PROP_TCP_PORT, "" + i2cpPort);
try { try {
I2PSession session = client.createSession(myPrivateKeyStream, opts); I2PSession session = client.createSession(myPrivateKeyStream, opts);
session.connect(); session.connect();

View File

@ -7,6 +7,7 @@ package net.i2p.client.streaming;
*/ */
public class I2PSocketOptions { public class I2PSocketOptions {
private long _connectTimeout; private long _connectTimeout;
public I2PSocketOptions() { public I2PSocketOptions() {
_connectTimeout = -1; _connectTimeout = -1;
} }
@ -16,6 +17,11 @@ public class I2PSocketOptions {
* *
* @return milliseconds to wait, or -1 if we will wait indefinitely * @return milliseconds to wait, or -1 if we will wait indefinitely
*/ */
public long getConnectTimeout() { return _connectTimeout; } public long getConnectTimeout() {
public void setConnectTimeout(long ms) { _connectTimeout = ms; } return _connectTimeout;
}
public void setConnectTimeout(long ms) {
_connectTimeout = ms;
}
} }

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay; package net.i2p.phttprelay;
/* /*
* free (adj.): unencumbered; not under the control of others * free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain * Written by jrandom in 2003 and released into the public domain
@ -71,8 +72,8 @@ public class CheckSendStatusServlet extends PHTTPRelayServlet {
} }
private boolean isKnownMessage(String target, String msgId) throws IOException { private boolean isKnownMessage(String target, String msgId) throws IOException {
if ( (target == null) || (target.trim().length() <= 0) ) return false; if ((target == null) || (target.trim().length() <= 0)) return false;
if ( (msgId == null) || (msgId.trim().length() <= 0) ) return false; if ((msgId == null) || (msgId.trim().length() <= 0)) return false;
File identDir = getIdentDir(target); File identDir = getIdentDir(target);
if (identDir.exists()) { if (identDir.exists()) {
File identFile = new File(identDir, "identity.dat"); File identFile = new File(identDir, "identity.dat");

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay; package net.i2p.phttprelay;
/* /*
* free (adj.): unencumbered; not under the control of others * free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain * Written by jrandom in 2003 and released into the public domain
@ -26,7 +27,10 @@ class LockManager {
_locks.add(target); _locks.add(target);
return; return;
} }
try { _locks.wait(1000); } catch (InterruptedException ie) {} try {
_locks.wait(1000);
} catch (InterruptedException ie) {
}
} }
} }
} }

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay; package net.i2p.phttprelay;
/* /*
* free (adj.): unencumbered; not under the control of others * free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain * Written by jrandom in 2003 and released into the public domain
@ -27,7 +28,7 @@ abstract class PHTTPRelayServlet extends HttpServlet {
public final static String ENV_BASEDIR = "phttpRelay.baseDir"; public final static String ENV_BASEDIR = "phttpRelay.baseDir";
/** match the clock fudge factor on the router, rather than importing the entire router cvs module */ /** match the clock fudge factor on the router, rather than importing the entire router cvs module */
public final static long CLOCK_FUDGE_FACTOR = 1*60*1000; public final static long CLOCK_FUDGE_FACTOR = 1 * 60 * 1000;
protected String buildURL(HttpServletRequest req, String path) { protected String buildURL(HttpServletRequest req, String path) {
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
@ -40,7 +41,7 @@ abstract class PHTTPRelayServlet extends HttpServlet {
} }
protected File getIdentDir(String target) throws IOException { protected File getIdentDir(String target) throws IOException {
if ( (_baseDir == null) || (target == null) ) throw new IOException("dir not specified to deal with"); if ((_baseDir == null) || (target == null)) throw new IOException("dir not specified to deal with");
File baseDir = new File(_baseDir); File baseDir = new File(_baseDir);
if (!baseDir.exists()) { if (!baseDir.exists()) {
boolean created = baseDir.mkdirs(); boolean created = baseDir.mkdirs();
@ -55,7 +56,7 @@ abstract class PHTTPRelayServlet extends HttpServlet {
super.init(config); super.init(config);
String dir = System.getProperty(ENV_BASEDIR); String dir = System.getProperty(ENV_BASEDIR);
if (dir == null) { if (dir == null) {
_log.warn("Base directory for the polling http relay system not in the environment [" + ENV_BASEDIR +"]"); _log.warn("Base directory for the polling http relay system not in the environment [" + ENV_BASEDIR + "]");
_log.warn("Setting the base directory to ./relayDir for " + getServletName()); _log.warn("Setting the base directory to ./relayDir for " + getServletName());
_baseDir = ".relayDir"; _baseDir = ".relayDir";
} else { } else {
@ -67,6 +68,7 @@ abstract class PHTTPRelayServlet extends HttpServlet {
public void log(String msg) { public void log(String msg) {
_log.debug(msg); _log.debug(msg);
} }
public void log(String msg, Throwable t) { public void log(String msg, Throwable t) {
_log.debug(msg, t); _log.debug(msg, t);
} }

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay; package net.i2p.phttprelay;
/* /*
* free (adj.): unencumbered; not under the control of others * free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain * Written by jrandom in 2003 and released into the public domain
@ -113,9 +114,9 @@ public class PollServlet extends PHTTPRelayServlet {
StringBuffer buf = new StringBuffer(64); StringBuffer buf = new StringBuffer(64);
int numBytes = 0; int numBytes = 0;
int c = 0; int c = 0;
while ( (c = in.read()) != -1) { while ((c = in.read()) != -1) {
if (c == (int)'&') break; if (c == (int) '&') break;
buf.append((char)c); buf.append((char) c);
numBytes++; numBytes++;
if (numBytes > 128) { if (numBytes > 128) {
log("Target didn't find the & after 128 bytes [" + buf.toString() + "]"); log("Target didn't find the & after 128 bytes [" + buf.toString() + "]");
@ -138,10 +139,10 @@ public class PollServlet extends PHTTPRelayServlet {
expire(identDir); expire(identDir);
File messageFiles[] = identDir.listFiles(); File messageFiles[] = identDir.listFiles();
resp.setStatus(CODE_OK); resp.setStatus(CODE_OK);
log("Sending back " + (messageFiles.length -1) + " messages"); log("Sending back " + (messageFiles.length - 1) + " messages");
ServletOutputStream out = resp.getOutputStream(); ServletOutputStream out = resp.getOutputStream();
DataHelper.writeDate(out, new Date(Clock.getInstance().now())); DataHelper.writeDate(out, new Date(Clock.getInstance().now()));
DataHelper.writeLong(out, 2, messageFiles.length -1); DataHelper.writeLong(out, 2, messageFiles.length - 1);
for (int i = 0; i < messageFiles.length; i++) { for (int i = 0; i < messageFiles.length; i++) {
if ("identity.dat".equals(messageFiles[i].getName())) { if ("identity.dat".equals(messageFiles[i].getName())) {
// skip // skip
@ -165,12 +166,12 @@ public class PollServlet extends PHTTPRelayServlet {
} }
} }
private final static long EXPIRE_DELAY = 60*1000; // expire messages every minute private final static long EXPIRE_DELAY = 60 * 1000; // expire messages every minute
private void expire(File identDir) throws IOException { private void expire(File identDir) throws IOException {
File files[] = identDir.listFiles(); File files[] = identDir.listFiles();
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
for (int i = 0 ; i < files.length; i++) { for (int i = 0; i < files.length; i++) {
if ("identity.dat".equals(files[i].getName())) { if ("identity.dat".equals(files[i].getName())) {
continue; continue;
} }
@ -197,7 +198,6 @@ public class PollServlet extends PHTTPRelayServlet {
} }
} }
private boolean isKnown(String target) throws IOException { private boolean isKnown(String target) throws IOException {
File identDir = getIdentDir(target); File identDir = getIdentDir(target);
if (identDir.exists()) { if (identDir.exists()) {

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay; package net.i2p.phttprelay;
/* /*
* free (adj.): unencumbered; not under the control of others * free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain * Written by jrandom in 2003 and released into the public domain
@ -112,7 +113,10 @@ public class RegisterServlet extends PHTTPRelayServlet {
fos = new FileOutputStream(identFile); fos = new FileOutputStream(identFile);
ident.writeBytes(fos); ident.writeBytes(fos);
} finally { } finally {
if (fos != null) try { fos.close(); } catch (IOException ioe) {} if (fos != null) try {
fos.close();
} catch (IOException ioe) {
}
} }
log("Identity registered into " + identFile.getAbsolutePath()); log("Identity registered into " + identFile.getAbsolutePath());
return true; return true;

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay; package net.i2p.phttprelay;
/* /*
* free (adj.): unencumbered; not under the control of others * free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain * Written by jrandom in 2003 and released into the public domain
@ -82,27 +83,26 @@ public class SendServlet extends PHTTPRelayServlet {
/** msgId parameter to access the check path servlet with (along side PARAM_SEND_TARGET) */ /** msgId parameter to access the check path servlet with (along side PARAM_SEND_TARGET) */
public final static String PARAM_MSG_ID = "msgId"; public final static String PARAM_MSG_ID = "msgId";
/* key=val keys sent back on registration */ /* key=val keys sent back on registration */
public final static String PROP_CHECK_URL = "statusCheckURL"; public final static String PROP_CHECK_URL = "statusCheckURL";
public final static String PROP_STATUS = "status"; public final static String PROP_STATUS = "status";
public final static String STATUS_OK = "accepted"; public final static String STATUS_OK = "accepted";
public final static String STATUS_UNKNOWN = "unknown"; public final static String STATUS_UNKNOWN = "unknown";
private final static String STATUS_CLOCKSKEW = "clockSkew_"; /** prefix for (local-remote) */ private final static String STATUS_CLOCKSKEW = "clockSkew_";
/** prefix for (local-remote) */
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletInputStream in = req.getInputStream(); ServletInputStream in = req.getInputStream();
try { try {
int contentLen = req.getContentLength(); int contentLen = req.getContentLength();
String firstLine = getFirstLine(in, contentLen); String firstLine = getFirstLine(in, contentLen);
if (firstLine == null) { if (firstLine == null) { return; }
return;
}
Map params = getParameters(firstLine); Map params = getParameters(firstLine);
String target = (String)params.get(PARAM_SEND_TARGET); String target = (String) params.get(PARAM_SEND_TARGET);
String timeoutStr = (String)params.get(PARAM_SEND_TIMEOUTMS); String timeoutStr = (String) params.get(PARAM_SEND_TIMEOUTMS);
String lenStr = (String)params.get(PARAM_SEND_DATA_LENGTH); String lenStr = (String) params.get(PARAM_SEND_DATA_LENGTH);
String remoteTimeStr = (String)params.get(PARAM_SEND_TIME); String remoteTimeStr = (String) params.get(PARAM_SEND_TIME);
long skew = 0; long skew = 0;
try { try {
long remTime = Long.parseLong(remoteTimeStr); long remTime = Long.parseLong(remoteTimeStr);
@ -114,7 +114,7 @@ public class SendServlet extends PHTTPRelayServlet {
log("Target [" + target + "] timeout [" + timeoutStr + "] length [" + lenStr + "] skew [" + skew + "]"); log("Target [" + target + "] timeout [" + timeoutStr + "] length [" + lenStr + "] skew [" + skew + "]");
if ( (skew > CLOCK_FUDGE_FACTOR) || (skew < 0 - CLOCK_FUDGE_FACTOR) ) { if ((skew > CLOCK_FUDGE_FACTOR) || (skew < 0 - CLOCK_FUDGE_FACTOR)) {
log("Attempt to send by a skewed router: skew = " + skew + "ms (local-remote)"); log("Attempt to send by a skewed router: skew = " + skew + "ms (local-remote)");
failSkewed(req, resp, skew); failSkewed(req, resp, skew);
} }
@ -141,18 +141,20 @@ public class SendServlet extends PHTTPRelayServlet {
fail(req, resp, "Unable to queue up the message for delivery"); fail(req, resp, "Unable to queue up the message for delivery");
} }
} finally { } finally {
try { in.close(); } catch (IOException ioe) {} try {
in.close();
} catch (IOException ioe) {
}
} }
} }
private String getFirstLine(ServletInputStream in, int len) throws ServletException, IOException { private String getFirstLine(ServletInputStream in, int len) throws ServletException, IOException {
StringBuffer buf = new StringBuffer(128); StringBuffer buf = new StringBuffer(128);
int numBytes = 0; int numBytes = 0;
int c = 0; int c = 0;
while ( (c = in.read()) != -1) { while ((c = in.read()) != -1) {
if (c == (int)'\n') break; if (c == (int) '\n') break;
buf.append((char)c); buf.append((char) c);
numBytes++; numBytes++;
if (numBytes > 512) { if (numBytes > 512) {
log("First line is > 512 bytes [" + buf.toString() + "]"); log("First line is > 512 bytes [" + buf.toString() + "]");
@ -173,8 +175,8 @@ public class SendServlet extends PHTTPRelayServlet {
int firstEq = line.indexOf('='); int firstEq = line.indexOf('=');
if (firstAmp > 0) { if (firstAmp > 0) {
key = line.substring(0, firstEq); key = line.substring(0, firstEq);
val = line.substring(firstEq+1, firstAmp); val = line.substring(firstEq + 1, firstAmp);
line = line.substring(firstAmp+1); line = line.substring(firstAmp + 1);
params.put(key, val); params.put(key, val);
} else { } else {
line = null; line = null;
@ -191,8 +193,8 @@ public class SendServlet extends PHTTPRelayServlet {
// known and valid (maybe we need to check the file format... naw, fuck it // known and valid (maybe we need to check the file format... naw, fuck it
String files[] = identDir.list(); String files[] = identDir.list();
// we skip 1 because of identity.dat // we skip 1 because of identity.dat
if (files.length -1 > _maxMessagesPerIdent) { if (files.length - 1 > _maxMessagesPerIdent) {
log("Too many messages pending for " + target + ": " + (files.length-1)); log("Too many messages pending for " + target + ": " + (files.length - 1));
return false; return false;
} else { } else {
return true; return true;
@ -238,28 +240,30 @@ public class SendServlet extends PHTTPRelayServlet {
byte buf[] = new byte[4096]; byte buf[] = new byte[4096];
while (remaining > 0) { while (remaining > 0) {
int read = in.read(buf); int read = in.read(buf);
if (read == -1) if (read == -1) break;
break;
remaining -= read; remaining -= read;
if (read > 0) if (read > 0) fos.write(buf, 0, read);
fos.write(buf, 0, read);
} }
} finally { } finally {
if (fos != null) { if (fos != null) {
try { fos.close(); } catch (IOException ioe) {} try {
fos.close();
} catch (IOException ioe) {
}
} }
if (remaining != 0) { if (remaining != 0) {
log("Invalid remaining bytes [" + remaining + " out of " + len + "] - perhaps message was cancelled partway through delivery? deleting " + file.getAbsolutePath()); log("Invalid remaining bytes [" + remaining + " out of " + len
+ "] - perhaps message was cancelled partway through delivery? deleting " + file.getAbsolutePath());
boolean deleted = file.delete(); boolean deleted = file.delete();
if (!deleted) if (!deleted) log("!!!Error deleting temporary file " + file.getAbsolutePath());
log("!!!Error deleting temporary file " + file.getAbsolutePath());
return false; return false;
} }
} }
return true; return true;
} }
private void sendSuccess(HttpServletRequest req, HttpServletResponse resp, String target, int msgId) throws IOException { private void sendSuccess(HttpServletRequest req, HttpServletResponse resp, String target, int msgId)
throws IOException {
ServletOutputStream out = resp.getOutputStream(); ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_OK).append('\n'); buf.append(PROP_STATUS).append('=').append(STATUS_OK).append('\n');
@ -298,20 +302,22 @@ public class SendServlet extends PHTTPRelayServlet {
String maxMessagesPerIdentStr = config.getInitParameter(PARAM_MAX_MESSAGES_PER_IDENT); String maxMessagesPerIdentStr = config.getInitParameter(PARAM_MAX_MESSAGES_PER_IDENT);
if (maxMessagesPerIdentStr == null) if (maxMessagesPerIdentStr == null)
throw new ServletException("Max messages per ident for the sending servlet required [" + PARAM_MAX_MESSAGES_PER_IDENT + "]"); throw new ServletException("Max messages per ident for the sending servlet required ["
+ PARAM_MAX_MESSAGES_PER_IDENT + "]");
try { try {
_maxMessagesPerIdent = Integer.parseInt(maxMessagesPerIdentStr); _maxMessagesPerIdent = Integer.parseInt(maxMessagesPerIdentStr);
} catch (Throwable t) { } catch (Throwable t) {
throw new ServletException("Valid max messages per ident for the sending servlet required [" + PARAM_MAX_MESSAGES_PER_IDENT + "]"); throw new ServletException("Valid max messages per ident for the sending servlet required ["
+ PARAM_MAX_MESSAGES_PER_IDENT + "]");
} }
} }
public static void main(String args[]) { public static void main(String args[]) {
String line = "target=pp0ARjQiB~IKC-0FsMUsPEMrwR3gxVBZGRYfEr1IzHI=&timeoutMs=52068&dataLength=2691&"; String line = "target=pp0ARjQiB~IKC-0FsMUsPEMrwR3gxVBZGRYfEr1IzHI=&timeoutMs=52068&dataLength=2691&";
Map props = getParameters(line); Map props = getParameters(line);
for (java.util.Iterator iter = props.keySet().iterator(); iter.hasNext(); ) { for (java.util.Iterator iter = props.keySet().iterator(); iter.hasNext();) {
String key = (String)iter.next(); String key = (String) iter.next();
String val = (String)props.get(key); String val = (String) props.get(key);
System.out.println("[" + key + "] = [" + val + "]"); System.out.println("[" + key + "] = [" + val + "]");
} }
} }

View File

@ -20,41 +20,31 @@ public class BasicEchoTestAnalyzer implements EchoTestAnalyzer {
SUMMARY_SIZE = summarySize; SUMMARY_SIZE = summarySize;
} }
private int events = 0, private int events = 0, packetLosses = 0, packetLossesDisconnect = 0, disconnects = 0, disconnectsRefused = 0,
packetLosses = 0, delayCount = 0, lastDelayPtr = 0;
packetLossesDisconnect=0, private long minDelay = Long.MAX_VALUE, maxDelay = 0, delaySum = 0;
disconnects = 0,
disconnectsRefused = 0,
delayCount=0,
lastDelayPtr = 0;
private long minDelay=Long.MAX_VALUE, maxDelay = 0, delaySum=0;
private long[] lastDelays = new long[SUMMARY_SIZE]; private long[] lastDelays = new long[SUMMARY_SIZE];
public synchronized void packetLossOccurred(boolean beforeDisconnect) { public synchronized void packetLossOccurred(boolean beforeDisconnect) {
System.out.println("1: Packet lost"+ System.out.println("1: Packet lost" + (beforeDisconnect ? " before disconnect" : "") + ".");
(beforeDisconnect?" before disconnect":"")+
".");
packetLosses++; packetLosses++;
if (beforeDisconnect) packetLossesDisconnect++; if (beforeDisconnect) packetLossesDisconnect++;
countEvent(); countEvent();
} }
public synchronized void successOccurred(long delay) { public synchronized void successOccurred(long delay) {
System.out.println("0: Delay = "+delay); System.out.println("0: Delay = " + delay);
if (delay > maxDelay) maxDelay=delay; if (delay > maxDelay) maxDelay = delay;
if (delay < minDelay) minDelay=delay; if (delay < minDelay) minDelay = delay;
delaySum+=delay; delaySum += delay;
delayCount++; delayCount++;
lastDelays[lastDelayPtr++]=delay; lastDelays[lastDelayPtr++] = delay;
lastDelayPtr%=SUMMARY_SIZE; lastDelayPtr %= SUMMARY_SIZE;
countEvent(); countEvent();
} }
public synchronized void disconnected(boolean refused) { public synchronized void disconnected(boolean refused) {
System.out.println("2: Disconnected"+ System.out.println("2: Disconnected" + (refused ? " (connection refused)" : "") + ".");
(refused?" (connection refused)":"")+
".");
disconnects++; disconnects++;
if (refused) disconnectsRefused++; if (refused) disconnectsRefused++;
countEvent(); countEvent();
@ -63,32 +53,36 @@ public class BasicEchoTestAnalyzer implements EchoTestAnalyzer {
private void countEvent() { private void countEvent() {
events++; events++;
if (events % REPORT_DELAY == 0) { if (events % REPORT_DELAY == 0) {
int packets = packetLosses+delayCount; int packets = packetLosses + delayCount;
long delaySummary=0; long delaySummary = 0;
for (int i=0;i<SUMMARY_SIZE;i++) { for (int i = 0; i < SUMMARY_SIZE; i++) {
delaySummary+=lastDelays[i]; delaySummary += lastDelays[i];
} }
System.out.println System.out.println("++++++++++++++++ ECHO STATISTICS +++++++++++++++++++++++++"
("++++++++++++++++ ECHO STATISTICS +++++++++++++++++++++++++"+ + "\n++ Number of total echo messages: "
"\n++ Number of total echo messages: "+packets+ + packets
"\n++ No response for "+packetLosses+ + "\n++ No response for "
"\n++ (of which "+ packetLossesDisconnect+ + packetLosses
" due to a disconnect)"+ + "\n++ (of which "
"\n++ Disconnects: "+disconnects+ + packetLossesDisconnect
"\n++ (of which "+disconnectsRefused+ + " due to a disconnect)"
" due to 'connection refused')"+ + "\n++ Disconnects: "
(disconnects>0 || true + disconnects
?"\n++ Average lost packets per disconnect: "+ + "\n++ (of which "
(packetLossesDisconnect/(float)disconnects) + disconnectsRefused
:"")+ + " due to 'connection refused')"
"\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++"+ + (disconnects > 0 || true ? "\n++ Average lost packets per disconnect: "
"\n++ Minimal delay: "+minDelay+ + (packetLossesDisconnect / (float) disconnects) : "")
"\n++ Average delay: "+(delaySum/(float)delayCount)+ + "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
"\n++ Maximal delay: "+maxDelay+ + "\n++ Minimal delay: "
(delayCount >=SUMMARY_SIZE + minDelay
?"\n++ Average delay over last " + SUMMARY_SIZE + ": "+(delaySummary/(float)SUMMARY_SIZE) + "\n++ Average delay: "
:"")+ + (delaySum / (float) delayCount)
"\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); + "\n++ Maximal delay: "
+ maxDelay
+ (delayCount >= SUMMARY_SIZE ? "\n++ Average delay over last " + SUMMARY_SIZE + ": "
+ (delaySummary / (float) SUMMARY_SIZE) : "")
+ "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
} }
} }
} }

View File

@ -15,5 +15,3 @@ public interface EchoTestAnalyzer {
} }

View File

@ -26,14 +26,13 @@ public class EchoTester extends Thread {
/** /**
* How long to wait between packets. Default is 6 seconds. * How long to wait between packets. Default is 6 seconds.
*/ */
private static long PACKET_DELAY= 6000; private static long PACKET_DELAY = 6000;
/** /**
* How many packets may be on the way before the connection is * How many packets may be on the way before the connection is
* seen as "broken" and disconnected. * seen as "broken" and disconnected.
*/ */
private static final long MAX_PACKETS_QUEUED=50; // unused private static final long MAX_PACKETS_QUEUED = 50; // unused
private EchoTestAnalyzer eta; private EchoTestAnalyzer eta;
private String host; private String host;
@ -41,21 +40,19 @@ public class EchoTester extends Thread {
// the following vars are synchronized via the lock. // the following vars are synchronized via the lock.
private Object lock = new Object(); private Object lock = new Object();
private long nextPacket=0; private long nextPacket = 0;
private long nextUnreceived=0; private long nextUnreceived = 0;
private boolean readerRunning=false; private boolean readerRunning = false;
public static void main(String[] args) { public static void main(String[] args) {
if (args.length == 3) if (args.length == 3) PACKET_DELAY = Long.parseLong(args[2]);
PACKET_DELAY = Long.parseLong(args[2]); new EchoTester(args[0], Integer.parseInt(args[1]), new BasicEchoTestAnalyzer());
new EchoTester(args[0], Integer.parseInt(args[1]),
new BasicEchoTestAnalyzer());
} }
public EchoTester(String host, int port, EchoTestAnalyzer eta) { public EchoTester(String host, int port, EchoTestAnalyzer eta) {
this.eta=eta; this.eta = eta;
this.host=host; this.host = host;
this.port=port; this.port = port;
start(); start();
} }
@ -70,20 +67,19 @@ public class EchoTester extends Thread {
Thread.sleep(PACKET_DELAY); Thread.sleep(PACKET_DELAY);
continue; continue;
} }
System.out.println("41: Connected to "+host+":"+port); System.out.println("41: Connected to " + host + ":" + port);
synchronized(lock) { synchronized (lock) {
nextUnreceived=nextPacket; nextUnreceived = nextPacket;
} }
Thread t = new ResponseReaderThread(s); Thread t = new ResponseReaderThread(s);
Writer w = new BufferedWriter(new OutputStreamWriter Writer w = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
(s.getOutputStream()));
while (true) { while (true) {
long no; long no;
synchronized(lock) { synchronized (lock) {
no = nextPacket++; no = nextPacket++;
} }
try { try {
w.write(no+" "+System.currentTimeMillis()+"\n"); w.write(no + " " + System.currentTimeMillis() + "\n");
w.flush(); w.flush();
} catch (SocketException ex) { } catch (SocketException ex) {
break; break;
@ -92,18 +88,16 @@ public class EchoTester extends Thread {
} }
s.close(); s.close();
t.join(); t.join();
synchronized(lock) { synchronized (lock) {
if (readerRunning) { if (readerRunning) {
System.out.println("*** WHY IS THIS THREAD STILL"+ System.out.println("*** WHY IS THIS THREAD STILL" + " RUNNING?");
" RUNNING?");
} }
while (nextUnreceived < nextPacket) { while (nextUnreceived < nextPacket) {
nextUnreceived++; nextUnreceived++;
eta.packetLossOccurred(true); eta.packetLossOccurred(true);
} }
if (nextUnreceived > nextPacket) { if (nextUnreceived > nextPacket) {
System.out.println("*** WTF? "+nextUnreceived+" > "+ System.out.println("*** WTF? " + nextUnreceived + " > " + nextPacket);
nextPacket);
} }
} }
eta.disconnected(false); eta.disconnected(false);
@ -123,29 +117,25 @@ public class EchoTester extends Thread {
private Socket s; private Socket s;
public ResponseReaderThread(Socket s) { public ResponseReaderThread(Socket s) {
this.s=s; this.s = s;
synchronized(lock) { synchronized (lock) {
readerRunning=true; readerRunning = true;
} }
start(); start();
} }
public void run() { public void run() {
try { try {
BufferedReader br = new BufferedReader(new InputStreamReader BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
(s.getInputStream()));
String line; String line;
int index; int index;
while ((line=br.readLine()) != null) { while ((line = br.readLine()) != null) {
if ((index=line.indexOf(" ")) == -1) if ((index = line.indexOf(" ")) == -1) continue;
continue;
long now, packetNumber, packetTime; long now, packetNumber, packetTime;
now = System.currentTimeMillis(); now = System.currentTimeMillis();
try { try {
packetNumber = Long.parseLong packetNumber = Long.parseLong(line.substring(0, index));
(line.substring(0,index)); packetTime = Long.parseLong(line.substring(index + 1));
packetTime = Long.parseLong
(line.substring(index+1));
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
System.out.println(ex.toString()); System.out.println(ex.toString());
continue; continue;
@ -161,7 +151,7 @@ public class EchoTester extends Thread {
nextUnreceived++; nextUnreceived++;
} }
} }
eta.successOccurred(now-packetTime); eta.successOccurred(now - packetTime);
} }
} catch (SocketException ex) { } catch (SocketException ex) {
// ignore // ignore
@ -169,8 +159,8 @@ public class EchoTester extends Thread {
ex.printStackTrace(); ex.printStackTrace();
System.exit(0); System.exit(0);
} }
synchronized(lock) { synchronized (lock) {
readerRunning=false; readerRunning = false;
} }
} }
} }