Fixed issue #8 - search for MAGIC bytes instead of just checking

This commit is contained in:
Christian Basler 2015-06-11 19:42:44 +02:00
parent effb2ac2fb
commit a053b64fe6

View File

@ -31,19 +31,21 @@ import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import static ch.dissem.bitmessage.entity.NetworkMessage.MAGIC_BYTES;
/** /**
* Creates protocol v3 network messages from {@link InputStream InputStreams} * Creates protocol v3 network messages from {@link InputStream InputStreams}
*/ */
class V3MessageFactory { class V3MessageFactory {
private static Logger LOG = LoggerFactory.getLogger(V3MessageFactory.class); private static Logger LOG = LoggerFactory.getLogger(V3MessageFactory.class);
public static NetworkMessage read(InputStream stream) throws IOException { public static NetworkMessage read(InputStream in) throws IOException {
if (testMagic(stream)) { findMagic(in);
String command = getCommand(stream); String command = getCommand(in);
int length = (int) Decode.uint32(stream); int length = (int) Decode.uint32(in);
byte[] checksum = Decode.bytes(stream, 4); byte[] checksum = Decode.bytes(in, 4);
byte[] payloadBytes = Decode.bytes(stream, length); byte[] payloadBytes = Decode.bytes(in, length);
if (testChecksum(checksum, payloadBytes)) { if (testChecksum(checksum, payloadBytes)) {
MessagePayload payload = getPayload(command, new ByteArrayInputStream(payloadBytes), length); MessagePayload payload = getPayload(command, new ByteArrayInputStream(payloadBytes), length);
@ -54,10 +56,6 @@ class V3MessageFactory {
} else { } else {
throw new IOException("Checksum failed for message '" + command + "'"); throw new IOException("Checksum failed for message '" + command + "'");
} }
} else {
LOG.debug("Failed test for MAGIC bytes");
return null;
}
} }
private static MessagePayload getPayload(String command, InputStream stream, int length) throws IOException { private static MessagePayload getPayload(String command, InputStream stream, int length) throws IOException {
@ -198,10 +196,19 @@ class V3MessageFactory {
return new String(bytes, 0, end, "ASCII"); return new String(bytes, 0, end, "ASCII");
} }
private static boolean testMagic(InputStream stream) throws IOException { private static void findMagic(InputStream in) throws IOException {
for (byte b : NetworkMessage.MAGIC_BYTES) { int pos = 0;
if (b != (byte) stream.read()) return false; for (int i = 0; i < 1620000; i++) {
byte b = (byte) in.read();
if (b == MAGIC_BYTES[pos]) {
pos++;
if (pos == MAGIC_BYTES.length) {
return;
} }
return true; } else {
pos = 0;
}
}
throw new IOException("Failed to fine MAGIC bytes in stream");
} }
} }