diff --git a/.gitignore b/.gitignore
index f16d5ba..3f1c084 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,15 @@
/dist/
/workingdirectory/
build.xml
+.idea
+target/
+pom.xml.tag
+pom.xml.releaseBackup
+pom.xml.versionsBackup
+pom.xml.next
+release.properties
+dependency-reduced-pom.xml
+buildNumber.properties
+.mvn/timing.properties
+# https://github.com/takari/maven-wrapper#usage-without-binary-jar
+.mvn/wrapper/maven-wrapper.jar
diff --git a/.idea/.gitignore b/.idea/.gitignore
deleted file mode 100644
index 5c98b42..0000000
--- a/.idea/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# Default ignored files
-/workspace.xml
\ No newline at end of file
diff --git a/.idea/ASAP.iml b/.idea/ASAP.iml
deleted file mode 100644
index 6ccdc21..0000000
--- a/.idea/ASAP.iml
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
deleted file mode 100644
index 207c086..0000000
--- a/.idea/misc.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
deleted file mode 100644
index 28f9e94..0000000
--- a/.idea/modules.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml
deleted file mode 100644
index e96534f..0000000
--- a/.idea/uiDesigner.xml
+++ /dev/null
@@ -1,124 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
deleted file mode 100644
index 35eb1dd..0000000
--- a/.idea/vcs.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF
index 59499bc..7def224 100644
--- a/META-INF/MANIFEST.MF
+++ b/META-INF/MANIFEST.MF
@@ -1,2 +1,3 @@
Manifest-Version: 1.0
+Main-Class: net.sharksystem.asap.cmdline.CmdLineUI
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..2c69f94
--- /dev/null
+++ b/README.md
@@ -0,0 +1,18 @@
+# ASAPJava
+Asynchronous Semantic Ad-hoc Protocol (ASAP) engine for Java
+
+# Maven Guide
+## Compile and run tests
+```
+mvn clean package
+```
+This compiles all files, runs tests and, if they succeed, compiles the jar. The compiled jar (ASAPJava-{Version}.jar) will be in your target/ folder.
+
+## Compile without tests
+This is needed in case you want to build the jar while your tests fail (which currently, they do fail).
+```
+mvn clean package -DskipTests
+```
+
+# Wiki
+Visit [the wiki](https://github.com/SharedKnowledge/ASAPJava/wiki) for all other information on what ASAP is and how to use it.
diff --git a/manifest.mf b/manifest.mf
index 1574df4..573d5a1 100644
--- a/manifest.mf
+++ b/manifest.mf
@@ -1,3 +1,4 @@
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
+Main-Class: net.sharksystem.asap.cmdline.CmdLineUI
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..2b2da25
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,70 @@
+
+
+ 4.0.0
+
+ net.sharksystem
+ ASAPJava
+ 0.7.0
+
+
+ 8
+ 8
+ 5.8.1
+ 1.8.1
+ 0.7.0
+
+
+
+
+ junit
+ junit
+ 4.13.2
+ test
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ 5.8.1
+ test
+
+
+
+
+ commons-io
+ commons-io
+ 2.11.0
+
+
+
+
+
+ com.sun.xml.bind
+ jaxb-impl
+ 3.0.2
+
+
+ org.junit.platform
+ junit-platform-suite-api
+ 1.8.1
+ test
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 2.22.1
+
+
+
+
+
\ No newline at end of file
diff --git a/src/main/java/META-INF/MANIFEST.MF b/src/main/java/META-INF/MANIFEST.MF
new file mode 100644
index 0000000..7def224
--- /dev/null
+++ b/src/main/java/META-INF/MANIFEST.MF
@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+Main-Class: net.sharksystem.asap.cmdline.CmdLineUI
+
diff --git a/src/main/java/net/sharksystem/SharkException.java b/src/main/java/net/sharksystem/SharkException.java
new file mode 100644
index 0000000..f084173
--- /dev/null
+++ b/src/main/java/net/sharksystem/SharkException.java
@@ -0,0 +1,14 @@
+package net.sharksystem;
+
+public class SharkException extends Exception {
+ public SharkException() { super(); }
+ public SharkException(String message) {
+ super(message);
+ }
+ public SharkException(String message, Throwable cause) {
+ super(message, cause);
+ }
+ public SharkException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/src/main/java/net/sharksystem/SharkNotSupportedException.java b/src/main/java/net/sharksystem/SharkNotSupportedException.java
new file mode 100644
index 0000000..81dce3a
--- /dev/null
+++ b/src/main/java/net/sharksystem/SharkNotSupportedException.java
@@ -0,0 +1,16 @@
+package net.sharksystem;
+
+public class SharkNotSupportedException extends RuntimeException {
+ public SharkNotSupportedException() {
+ super();
+ }
+ public SharkNotSupportedException(String message) {
+ super(message);
+ }
+ public SharkNotSupportedException(String message, Throwable cause) {
+ super(message, cause);
+ }
+ public SharkNotSupportedException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAP.java b/src/main/java/net/sharksystem/asap/ASAP.java
new file mode 100644
index 0000000..821207a
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAP.java
@@ -0,0 +1,129 @@
+package net.sharksystem.asap;
+
+import java.util.Random;
+
+public class ASAP {
+ public static final int TRANSIENT_ERA = Integer.MAX_VALUE;
+ public static final int INITIAL_ERA = 0;
+ public static final int MIN_ERA = INITIAL_ERA;
+ public static final int MAX_ERA = Integer.MAX_VALUE-1;
+
+ public static int nextEra(int workingEra) {
+ if(workingEra == ASAP.MAX_ERA) {
+ return ASAP.INITIAL_ERA;
+ }
+ return workingEra+1;
+ }
+
+ public static int previousEra(int workingEra) {
+ if(workingEra == ASAP.INITIAL_ERA) {
+ return ASAP.MAX_ERA;
+ }
+ return workingEra-1;
+ }
+
+ /**
+ * produces a unique id - is made up by current time in millis added with some random digits.
+ * @return
+ */
+ public static String createUniqueID() {
+ long now = System.currentTimeMillis();
+ long nowUnchanged = now;
+
+ /* now is a 64 bit value. Actually, only 63 bits are relevant because it is positive value.
+ Moreover, we are already in the 21. century - could reduce bit even more. We ignore that obvious fact
+ at first.
+
+ Calculations: 2^64 = 1,8.. * 10^19; we take a..z and A..Z and 0..9 -> 62 digits
+ 62^11 = 5,2.. * 10^19 we need 11 digits
+ */
+
+ int randomDigits = 3;
+ int timeDigits = 11;
+ int digits = timeDigits + randomDigits;
+ int basis = 62;
+
+ /*
+ 0..9 --> 0..9
+ 10..35 -> a..z
+ 36..61 -> A..Z
+ */
+
+ char[] idChars = new char[digits];
+ // init with random number
+ for(int i = 0; i < digits; i++) idChars[i] = '0';
+
+ // let's fill it with code time stamp
+ int i = 0;
+ long rest = 0;
+ while(now > 0) {
+ rest = now % basis; // rest is number [0,63]
+ now /= basis;
+
+ idChars[i++] = ASAP.int2charID((int) rest);
+ }
+
+ // set index
+ i = timeDigits;
+
+ // random digits
+ long rValue = now + nowUnchanged;
+ Random random = new Random(rValue);
+ //char lastC = ' '; // not value space
+ while(i < digits) {
+ int r = random.nextInt(basis);
+ char c = ASAP.int2charID(r);
+ //if(c == lastC) continue;
+ idChars[i++] = c;
+ rValue = (rValue * r * nowUnchanged) % basis;
+ random = new Random(rValue);
+ //random.setSeed(rValue);
+ }
+
+ return new String(idChars);
+ }
+
+ private static char int2charID(int value) {
+ // convert value into valid values;
+ // 0..9 -> 0..9
+ if(value <= 9) {
+ return (char)((int)'0' + value);
+ } else {
+ value -= 10;
+ // a..z
+ if(value <= 25) {
+ return (char)((int)'a' + value);
+ } else {
+ // A..Z
+ value -= 26;
+ return (char)((int)'A' + value);
+ }
+ }
+ }
+
+ /**
+ *
+ * This method test if an era is within (or on the edge of) an era - range described by first and last era.
+ * @param era era that is tested. Is in within a given range
+ * @param eraFirst first era of that range.
+ * @param eraLast last era of that range
+ * @return true - era is in that range or on the edge, false otherwise
+ */
+ public static boolean isEraInRange(int era, int eraFirst, int eraLast) {
+ // deal wrapping around era numbers
+ if(eraLast - eraFirst >= 0) { // not wrapped around
+ // [init].... [eraFirst] ++++ [eraLast] ..... [max]
+ return (era >= eraFirst && era <= eraLast);
+ }
+ // else: wrapped around:
+ /*
+ [init]++++++++++++++ [eraLast] .......... [eraFirst] +++++++++[max]
+ (a) (b) (c)
+ */
+ return (
+ isEraInRange(era, eraFirst, ASAP.MAX_ERA) // c)
+ ||
+ isEraInRange(era, ASAP.INITIAL_ERA, eraLast) // a)
+ );
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPChannel.java b/src/main/java/net/sharksystem/asap/ASAPChannel.java
new file mode 100644
index 0000000..fe995ea
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPChannel.java
@@ -0,0 +1,45 @@
+package net.sharksystem.asap;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Set;
+
+public interface ASAPChannel {
+ CharSequence getOwner() throws IOException;
+ CharSequence getUri() throws IOException;
+ Set getRecipients() throws IOException;
+ HashMap getExtraData() throws IOException;
+ void putExtraData(String key, String value) throws IOException;
+ void removeExtraData(String key) throws IOException;
+
+ /**
+ * Get all message in this channel, including received messages. Same as getMessages(true);
+ * @return
+ * @throws IOException
+ */
+ ASAPMessages getMessages() throws IOException;
+
+ /**
+ * Get messages in this channel only (most probably sent) from this peer or also received messages
+ * @param sentMessagesOnly
+ * @return
+ * @throws IOException
+ */
+ ASAPMessages getMessages(boolean sentMessagesOnly) throws IOException, ASAPException;
+
+ /**
+ * Get all message (including received messages). Compare Object helps to bring messages in order.
+ *
+ * @param compare
+ * @return
+ * @throws IOException
+ */
+ ASAPMessages getMessages(ASAPMessageCompare compare) throws IOException, ASAPException;
+
+ /**
+ * Add a message to this channel - in other words: broadcast a message into this channel.
+ * @param message
+ * @throws IOException
+ */
+ void addMessage(byte[] message) throws IOException;
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPChannelContentChangedListener.java b/src/main/java/net/sharksystem/asap/ASAPChannelContentChangedListener.java
new file mode 100644
index 0000000..49339c6
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPChannelContentChangedListener.java
@@ -0,0 +1,5 @@
+package net.sharksystem.asap;
+
+public interface ASAPChannelContentChangedListener {
+ void asapChannelContentChanged(CharSequence format, CharSequence uri, int era);
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPChannelContentChangedListenerManagement.java b/src/main/java/net/sharksystem/asap/ASAPChannelContentChangedListenerManagement.java
new file mode 100644
index 0000000..7724bb1
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPChannelContentChangedListenerManagement.java
@@ -0,0 +1,16 @@
+package net.sharksystem.asap;
+
+public interface ASAPChannelContentChangedListenerManagement {
+ /**
+ * Add listener for changes in ASAP environment
+ * @param listener listener which is to be added
+ */
+ void addASAPChannelContentChangedListener(CharSequence format, ASAPChannelContentChangedListener listener);
+
+ /**
+ * Remove changes listener
+ * @param listener listener which is to be removed
+ */
+ void removeASAPChannelContentChangedListener(CharSequence format, ASAPChannelContentChangedListener listener);
+
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPChunk.java b/src/main/java/net/sharksystem/asap/ASAPChunk.java
new file mode 100644
index 0000000..515ac33
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPChunk.java
@@ -0,0 +1,92 @@
+package net.sharksystem.asap;
+
+import net.sharksystem.asap.engine.MessagesContainer;
+
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * An ASAP chunk is a set of message with the same format, same uri and same era.
+ *
+ * Usually, there will be a running ASAP protocol engine that writes received messages into
+ * chunks and delivers chunks to peers during an encounter
+ *
+ * @author thsc
+ */
+public interface ASAPChunk extends MessagesContainer {
+ /**
+ *
+ * @return number of message in that chunk
+ */
+ int getNumberMessage();
+
+ /**
+ * URI of all messages within that chunk
+ * @return
+ * @throws IOException
+ */
+ String getUri() throws IOException;
+
+ /**
+ *
+ * @return iterator of all messages in the chunk
+ * @throws IOException
+ */
+ Iterator getMessages() throws IOException;
+
+ /**
+ * remove that chunk.. drop all object references after
+ * calling this methods. Further calls on this object
+ * have an undefined behaviour.
+ */
+ public void drop();
+
+ /**
+ *
+ * @return era all messages in that chunk
+ * @throws IOException
+ */
+ public int getEra() throws IOException;
+
+ /**
+ * Handle this methode with great care.
+ * It will most probable disappear of we find time to re-implement the PKI projects. Until then:
+ *
+ * A chunk behaves like an in- or outbox in an mail system. Sometimes a chunk is both.
+ * An ASAP peer offers a send message which is the preferred and recommended way to send messages.
+ *
+ * A peer behaves pretty simple internally. A message that is ought to be sent is stored in
+ * a chunk with current era. Received messages are stored in chunks as well. There is no need
+ * to change those chunks from any application.
+ *
+ * Peers can also be asked to re-deliver received messages. In that case, an application could think
+ * of managing such chunks to drop message (usually whole chunks) which are not meant to be
+ * re-delivered. Actually, it is not a really good idea. But we did. And we haven't not yet found time
+ * to take it out. And we need a running public key infrastructure.
+ *
+ * Furthermore, an ASAP peer keeps a list of its encounters. It can figure out the last era
+ * in which another peer was met. If they have never met before the initial era would be taken in
+ * its place.
+ *
+ * Now, default behaviour of a peer is to transmit all messages from this last-met-era
+ * until current era.
+ *
+ * Sometimes, it seemed to be efficient to manipulate those chunks to slightly change the set
+ * of delivered messages. I our decentralized PKI, we decided to implement the certificate
+ * storage as decorator of a chunk storage. That's actually quite efficient but requires
+ * a lot of explaining and hinders us to change the internal structure.
+ *
+ * Unfortunately, it forced us to make this feature public. And here we are. You can add a message
+ * to a chunk. You should not do it until you are absolutely sure what you are doing.
+ * It is something of a hack. Efficient yet but not good.
+ *
+ * @param messageAsBytes
+ * @throws IOException
+ * @see net.sharksystem.asap.ASAPPeer#sendASAPMessage(CharSequence, CharSequence, byte[])
+ */
+ void addMessage(byte[] messageAsBytes) throws IOException;
+
+ List getASAPHopList();
+
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPChunkStorage.java b/src/main/java/net/sharksystem/asap/ASAPChunkStorage.java
new file mode 100644
index 0000000..dba4fce
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPChunkStorage.java
@@ -0,0 +1,40 @@
+package net.sharksystem.asap;
+
+import net.sharksystem.asap.engine.ASAPInternalChunk;
+
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * There is a chunk storage for each format. It offers methods
+ * to get (and create) and remove (drop) chunks.
+ *
+ * Be careful. In most cases, there will be an ASAP protocol engine that writes data
+ * in chunks and reads and transmits messages to encountered peers.
+ *
+ * @author thsc
+ */
+public interface ASAPChunkStorage {
+ String getFormat();
+
+ ASAPInternalChunk getChunk(CharSequence uri, int era) throws IOException;
+
+ boolean existsChunk(CharSequence uri, int era) throws IOException;
+
+ List getChunks(int era) throws IOException;
+
+ void dropChunks(int era) throws IOException;
+
+ /**
+ *
+ * @param uri chunk storage uri
+ * @param toEra newest era
+ * @return a chunk cache which hides details of era
+ * @throws IOException
+ */
+ ASAPMessages getASAPMessages(CharSequence uri, int toEra) throws IOException;
+
+ ASAPMessages getASAPMessages(CharSequence uri, int fromEra, int toEra) throws IOException;
+
+ ASAPMessages getASAPMessages(String uri) throws ASAPException, IOException;
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPConnectionHandler.java b/src/main/java/net/sharksystem/asap/ASAPConnectionHandler.java
new file mode 100644
index 0000000..b1c0145
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPConnectionHandler.java
@@ -0,0 +1,49 @@
+package net.sharksystem.asap;
+
+import net.sharksystem.asap.protocol.ASAPConnection;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Set;
+
+public interface ASAPConnectionHandler {
+ /**
+ * Ask the entity to run an ASAP session based on this point-to-point connection.
+ * @param is stream to read from
+ * @param os stream to write into
+ * @param encrypt encrypt this point-to-point communication
+ * @param sign sign this point-to-point communication
+ * @param appsWhiteList if not null - only message from this app (synonym: with this format)
+ * within that list are handled. All other messages are ignored
+ * @param appsBlackList if not null - message from this app (synonym: with this format)
+ * are not handled. Overwrites white list entries.
+ * @return
+ * @throws IOException
+ * @throws ASAPException
+ */
+ ASAPConnection handleConnection(
+ InputStream is, OutputStream os, boolean encrypt, boolean sign,
+ Set appsWhiteList, Set appsBlackList
+ ) throws IOException, ASAPException;
+
+ ASAPConnection handleConnection(
+ InputStream is, OutputStream os, boolean encrypt, boolean sign, ASAPEncounterConnectionType connectionType,
+ Set appsWhiteList, Set appsBlackList
+ ) throws IOException, ASAPException;
+
+ /**
+ *
+ * Ask the entity to run an ASAP session based on this point-to-point connection. Message are neither
+ * encrypted nor signed. All formats are accepted in principle.
+ * @param is stream to read from
+ * @param os stream to write into
+ * @return
+ * @throws IOException
+ * @throws ASAPException
+ */
+ ASAPConnection handleConnection(InputStream is, OutputStream os) throws IOException, ASAPException;
+
+ ASAPConnection handleConnection(InputStream inputStream, OutputStream outputStream,
+ ASAPEncounterConnectionType connectionType) throws IOException, ASAPException;
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPEncounterConnectionType.java b/src/main/java/net/sharksystem/asap/ASAPEncounterConnectionType.java
new file mode 100644
index 0000000..ee533f2
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPEncounterConnectionType.java
@@ -0,0 +1,26 @@
+package net.sharksystem.asap;
+
+public enum ASAPEncounterConnectionType {
+ UNKNOWN ((byte) 0),
+ AD_HOC_LAYER_2_NETWORK ((byte) 1),
+ ASAP_HUB ((byte) 2),
+ INTERNET ((byte) 3),
+ ONION_NETWORK ((byte) 4);
+
+ private final byte type;
+
+ ASAPEncounterConnectionType(byte type) {
+ this.type = type;
+ }
+
+ public String toString() {
+ switch(this.type) {
+ case 0: return "unknown";
+ case 1: return "ad-hoc";
+ case 2: return "hub";
+ case 3: return "internet";
+ case 4: return "onion";
+ default: return "
+ * We could of course ignore this somewhat more complex environment and create a connection whenever possible and
+ * run an ASAP session. That not very efficient, though. It has even the tendency to be a considerable wast of
+ * resources. Why is that?
+ *
+ * Take ad-hoc networks as an example: A connection can be established within a given radius, like 10m with Bluetooth.
+ * A connection gets lost if two devices are over that threshold and can be re-established if they get closer. This
+ * leads to flickering effects. Connection gone / re-established / gone again etc. That's ok and useful if we are about
+ * implementing streaming services. But we war not. ASAP is basically meant to be platform for distributed apps which
+ * are based on the command pattern. There are no streams but data packages.
+ *
+ * Application developers will have a pretty good understanding of how often such messages are created. Even very fast
+ * human writers will barely produce more than a message per second, presumably far less. Exchange rate in a sensor
+ * network observing outside temperature is better be measured in hours than minutes. This will be different in
+ * industrial processes. Apparently: It depends on the application scenario. We want to give application developers
+ * as much help for optimization as possible. That is one way to safe most probably a lot of energy.
+ *
+ * ASAP is an opportunistic protocol. Connections should be established whenever possible. This could and will be a
+ * serious leak on resources in a multi-protocol environment. It is hardly useful that two smartphones create a
+ * Bluetooth and a Wifi-direct connection if they can. One is sufficient.
+ *
+ * An encounter manager deals with those problems. It is highly recommended to use it. We do, see e.g. our ASAPAndroid
+ * lib which is even more highly recommend.
+ */
+public interface ASAPEncounterManager {
+ /**
+ * Other devices can be detected by a point-to-point protocol. This method is to be called before a connection
+ * is established.
+ *
+ * It can be checked when a last encounter happened. This is most useful e.g. in ad-hoc networks. Communication can
+ * get lost by a (slight) movement and could be reestablished a moment later. A kind of cool-down-period can be
+ * defined.
+ *
+ * Peers could communicate over different channels. Same argument: It can be decided not to establish
+ * a connection due to an existing one over another protocol.
+ * @param addressOrPeerID address of remote device or a peer id. It is only used as an index, an id.
+ * There will be no attempts to establish a connection.
+ * @param connectionType Describes the connection that is planned to be established.
+ * @return true: a connection should be established or not.
+ * @see ASAPEncounterConnectionType
+ */
+ boolean shouldCreateConnectionToPeer(CharSequence addressOrPeerID, ASAPEncounterConnectionType connectionType);
+
+ /**
+ * Encounter manager forgets about its previous encounter. It will re-connect whenever possible.
+ * Gives peers a chance enforce reconnection if something changed o their side.
+ */
+ void forgetPreviousEncounter();
+
+ /**
+ * A connection to another device was established. This method can be called to handle this new connection.
+ * It can lead to an immediate shutdown, e.g. the other device already made a successful attempt to connect e.g.
+ * over another protocol.
+ *
+ * In a lot of cases an ASAP session will be launched.
+ *
+ * @param streamPair most likely a socket that is can be used for an ASAP session.
+ * @throws IOException something can go wrong when sending data. This object has no obligation to deal with this.
+ */
+ void handleEncounter(StreamPair streamPair, ASAPEncounterConnectionType connectionType) throws IOException;
+
+ /**
+ * This method is a variant of the one with less parameters.
+ *
+ * Here is the catch:
+ *
+ * We have a race condition in any ad-hoc network based on this library. What happens if both devices come into
+ * sending range?
+ *
+ *
+ *
Each asks this object if it should establish a connection by calling shouldConnect. It is highly likely
+ * that both side get same answer. Let's assume it is a yes.
+ *
Both would open a passive endpoint (most likely a server socket). In most cases it is already open
+ * before the previous step. In any case..
+ *
Both would try to establish a connection to the other side... An here starts the race...
+ *
Let's assume Alice and Bob are in that situation: Alice would recognize an connection attempt from
+ * Bob on her server socket. She is also aware that she is also doing a connection attempt to Bob. That's in the
+ * nature of this process. We do not want this. We do not want to parallel connections between those two devices.
+ * One should be canceled. But what: Alice -> Bob or Bob -> Alice ?
+ *
Bob is in the same situation. That problem arose when working with Bluetooth. It happens very often.
+ * This simple solution does not work: If we see a connection attempt on our server we drop out active
+ * connection attempt. Both side would do the same and both connection attempts are canceled. That is the race
+ * condition.
+ *
+ *
+ *
+ * This problem can be solved by adding an additional parameter. This boolean value states if this method is
+ * called by an initiator. What is that? A process that create e.g. a client socket is - per definition -
+ * an initiator. It initiated this connection. A server socket waits for connection attempts and is
+ * - per definition - no initiator. Please, choose very carefully this parameter. The race condition is solved
+ * by an implementation of this interface.
+ *
+ * If you are interested: Here is an idea of an implementation.
+ *
+ *
It is checked if there is an open connection to the other side before anything other happens.
+ * If so: stream pair is closed and we are ready here.
+ *
Both sides exchange a random value over this stream pair. One side will be initiator - the other not.
+ * (If you chose that parameter carefully). No we can decide:
+ * What is the random number of the initiator and what is the non-initiator value.
+ *
Is the initiator value smaller than the non-initial value? If so:
+ * We let this thread sleep a little while. We have produced an asymmetry. One process waits, the other not.
+ *
+ *
After wake-up: We check again if there is already a connection established. If so - there was a race
+ * condition and we solved it. If not - we establish a connection.
+ *
+ *
+ * You should call this variant in any ad-hoc network. You should also uses this variant if you have a fully
+ * symmetric situation - both devices offer a port to connect to any make and active attempt to connect.
+ *
+ * @param streamPair
+ * @param initiator
+ * @throws IOException
+ * @see ASAPEncounterManager#handleEncounter(StreamPair, ASAPEncounterConnectionType)
+ */
+ void handleEncounter(StreamPair streamPair, ASAPEncounterConnectionType connectionType, boolean initiator) throws IOException;
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPEncounterManagerAdmin.java b/src/main/java/net/sharksystem/asap/ASAPEncounterManagerAdmin.java
new file mode 100644
index 0000000..dcf6120
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPEncounterManagerAdmin.java
@@ -0,0 +1,79 @@
+package net.sharksystem.asap;
+
+import java.util.Date;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * That's the admin interface of an encounter manager. It allows deny list management.
+ * A deny list contains peerIDs. The encounter manager must not establish new connections to
+ * those peers. There can be several reasons (security (peer is not considered trustworthy),
+ * network topology (see considerations of a large scale ad-hoc network with limited
+ * connections on each peer).
+ *
+ * Future enhancements:
+ *
define a point to point encryption policy.
+ *
define what connections types are acceptable (Internet, Hub, Ad-hoc, Onion)
+ */
+public interface ASAPEncounterManagerAdmin {
+ /**
+ * @return set of ID to which an open connection exists right now.
+ */
+ Set getConnectedPeerIDs();
+
+ /**
+ *
+ * @param peerID peerID
+ * @return connection type of existing connection with given peer
+ * @throws ASAPException if no connection to that peer exists
+ */
+ ASAPEncounterConnectionType getConnectionType(CharSequence peerID) throws ASAPException;
+
+ /**
+ * Add a peerID to what no connection should be established.
+ * Note: Adding a peer to the deny list does not necessarily terminate an
+ * existing connection to that peer.
+ * @param peerID
+ */
+ void addToDenyList(CharSequence peerID);
+
+ /**
+ * Remove a peerID from deny list
+ * @param peerID
+ */
+ void removeFromDenyList(CharSequence peerID);
+
+ /**
+ * Get PeerID set to which no connection should be established
+ * @return
+ */
+ Set getDenyList();
+
+ /**
+ * remove all entries from deny list
+ */
+ void clearDenyList();
+
+ /**
+ * Cancel a connection to a peer. This method call does not change the deny list.
+ * @param peerID
+ */
+ void closeEncounter(CharSequence peerID);
+
+
+ /**
+ *
+ * @return information about last enocunter of a certain peer (described by its id)
+ */
+ Map getEncounterTime();
+
+ /**
+ * Peers exchange data during an encounter. In certain circumstances, ad-hoc networks show a feature that can be
+ * described es flickering. Devices might have reached communication range. A little shift can lead to connection
+ * lost. A little move backwards can bring them back in range. Connection establishment is a time-consuming task,
+ * though. Each encounter manager waits a while before it re-connects to a peer.
+ *
+ * @return time in milliseconds (aka 'cool down periode')
+ */
+ long getTimeBeforeReconnect();
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPEncounterManagerImpl.java b/src/main/java/net/sharksystem/asap/ASAPEncounterManagerImpl.java
new file mode 100644
index 0000000..554896f
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPEncounterManagerImpl.java
@@ -0,0 +1,475 @@
+package net.sharksystem.asap;
+
+import net.sharksystem.SharkException;
+import net.sharksystem.asap.utils.DateTimeHelper;
+import net.sharksystem.fs.ExtraDataFS;
+import net.sharksystem.asap.protocol.ASAPConnection;
+import net.sharksystem.asap.protocol.ASAPConnectionListener;
+import net.sharksystem.asap.utils.ASAPSerialization;
+import net.sharksystem.asap.utils.PeerIDHelper;
+import net.sharksystem.utils.streams.StreamPair;
+import net.sharksystem.utils.Log;
+
+import java.io.*;
+import java.util.*;
+
+public class ASAPEncounterManagerImpl implements
+ ASAPEncounterManager, ASAPEncounterManagerAdmin, ASAPConnectionListener {
+ public static final long DEFAULT_WAIT_BEFORE_RECONNECT_TIME = 60000; // 60 seconds == 1 minute
+ public static final long DEFAULT_WAIT_TO_AVOID_RACE_CONDITION = 500; // milliseconds - worked fine with BT.
+ public static final String DATASTORAGE_FILE_EXTENSION = "em";
+ private static final CharSequence ENCOUNTER_MANAGER_DENY_LIST_KEY = "denylist";
+ private final CharSequence peerID;
+ private ExtraDataFS extraDataStorage = null;
+
+ private int randomValue;
+ private long waitBeforeReconnect;
+ private ASAPConnectionHandler asapConnectionHandler; // object that will eventually run the ASAP session
+
+ /*
+ PeerID --[peerRemoteAddress]--(n)--> remoteAddress
+ remoteAddressORPeerID --[openStreamPairs]--(1)--> StreamPair
+ remoteAddressORPeerID --[encounterDate]--(1)--> Date
+ ASAPConnection --[openASAPConnections]--(1)--> remoteAddressORPeerID
+ */
+
+ /**
+ * We keep all open stream pairs indexed by their remote address to avoid identical connections and 'flickering'
+ * remote address -> stream pair
+ */
+ private Map openStreamPairs = new HashMap<>();
+
+ /** open ASAP connections with their stream pair: asap connection -> remote address */
+ private Map openASAPConnections = new HashMap<>();
+
+ /** remember last encounter: remote address -> date */
+ private Map encounterDate = new HashMap<>();
+
+ /** remember remote address of peers (they can have more than one): peerID -> remote address */
+ private Map> peerRemoteAddresses = new HashMap<>();
+
+ public ASAPEncounterManagerImpl(ASAPConnectionHandler asapConnectionHandler, CharSequence peerID)
+ throws SharkException, IOException {
+ this(asapConnectionHandler, peerID, DEFAULT_WAIT_BEFORE_RECONNECT_TIME);
+ }
+
+ public ASAPEncounterManagerImpl(ASAPConnectionHandler asapConnectionHandler, CharSequence peerID,
+ long waitingPeriod, CharSequence rootFolder) throws SharkException, IOException {
+ this.asapConnectionHandler = asapConnectionHandler;
+ this.peerID = peerID;
+ this.randomValue = new Random(System.currentTimeMillis()).nextInt();
+ this.waitBeforeReconnect = waitingPeriod;
+
+ if(rootFolder != null && rootFolder.length() > 0) {
+ // create folder
+ this.extraDataStorage = new ExtraDataFS(rootFolder + "/" + ENCOUNTER_MANAGER_DENY_LIST_KEY, DATASTORAGE_FILE_EXTENSION);
+ this.restoreDenyList();
+ }
+ }
+
+ public ASAPEncounterManagerImpl(ASAPConnectionHandler asapConnectionHandler, CharSequence peerID,
+ long waitingPeriod) throws SharkException, IOException {
+ this(asapConnectionHandler, peerID, waitingPeriod, null);
+ }
+
+ private boolean coolDownOver(CharSequence id, ASAPEncounterConnectionType connectionType) {
+ Date now = new Date();
+ Date lastEncounter = this.encounterDate.get(id);
+
+ if(lastEncounter == null) {
+ Log.writeLog(this, this.toString(),
+ "device/peer not in encounteredDevices - add "
+ + DateTimeHelper.long2ExactTimeString(now.getTime()));
+ // this.encounterDate.put(id, now); do not enter it into that list before (!!) a connection is established
+ return true;
+ }
+
+ // calculate reconnection time
+ Log.writeLog(this, this.toString(), "this.waitBeforeReconnect == " + this.waitBeforeReconnect);
+
+ // get current time, in its incarnation as date
+ long nowInMillis = now.getTime();
+ long shouldReconnectIfBeforeInMillis = nowInMillis - this.waitBeforeReconnect;
+ Date shouldReconnectIfBefore = new Date(shouldReconnectIfBeforeInMillis);
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("\n");
+ sb.append(DateTimeHelper.long2ExactTimeString(nowInMillis));
+ sb.append(" == now\n");
+ sb.append(DateTimeHelper.long2ExactTimeString(shouldReconnectIfBeforeInMillis));
+ sb.append(" == should reconnect if met before that moment\n");
+ sb.append(DateTimeHelper.long2ExactTimeString(lastEncounter.getTime()));
+ sb.append(" == last encounter");
+ Log.writeLog(this, this.toString(), sb.toString());
+
+ // known peer
+ Log.writeLog(this, this.toString(), "device/peer (" + id + ") in encounteredDevices list?");
+ // it was in the list
+ if(lastEncounter.before(shouldReconnectIfBefore)) {
+ Log.writeLog(this, this.toString(), "yes - should connect: " + id);
+ // remember that and overwrite previous entry
+ /* that was a nasty bug since this method is called before establishing a connection
+ * AND after connection establishment and before lauching an ASAP session
+ */
+ // this.encounterDate.put(id, now);
+ return true;
+ }
+
+ Log.writeLog(this, this.toString(), "should not connect - recently met: " + id);
+ return false;
+ }
+
+ @Override
+ public boolean shouldCreateConnectionToPeer(CharSequence remoteAdressOrPeerID,
+ ASAPEncounterConnectionType connectionType) {
+ Log.writeLog(this, this.toString(), "should connect to " + remoteAdressOrPeerID + " ?");
+ // on deny list?
+ if(this.denyList.contains(remoteAdressOrPeerID)) return false;
+ Log.writeLog(this, this.toString(), remoteAdressOrPeerID + " not on deny list");
+
+ // do we have a connection under a peerID?
+ StreamPair streamPair = this.openStreamPairs.get(remoteAdressOrPeerID);
+ if(streamPair != null) {
+ return false;
+ } else {
+ Log.writeLog(this, this.toString(), remoteAdressOrPeerID + " no parallel open connection");
+ }
+
+ // we know this peer and it is still in cool down period
+ if(!this.coolDownOver(remoteAdressOrPeerID, connectionType)) return false;
+
+ // is this id a remote adress?
+ Set remoteAddresses = this.peerRemoteAddresses.get(remoteAdressOrPeerID);
+ if(remoteAddresses == null) {
+ // we do not know this peer with no address - connect
+ return true;
+ }
+
+ // is there an open connection with any of those addresses?
+ for(CharSequence remoteAddress : remoteAddresses) {
+ streamPair = this.openStreamPairs.get(remoteAddress);
+ if(streamPair != null) {
+ // if there is a single reason not to connect - we do not connect
+ if(!this.coolDownOver(remoteAddress, connectionType)) return false;
+ }
+ }
+
+ // no open connection and cool down period over for any known address - connect
+ return true;
+ }
+
+ @Override
+ public void forgetPreviousEncounter() {
+ this.encounterDate = new HashMap<>();
+ }
+
+ @Override
+ public void handleEncounter(StreamPair streamPair, ASAPEncounterConnectionType connectionType) throws IOException {
+ this.handleEncounter(streamPair, connectionType, false, false);
+ }
+
+ @Override
+ public void handleEncounter(StreamPair streamPair, ASAPEncounterConnectionType connectionType, boolean initiator)
+ throws IOException {
+
+ this.handleEncounter(streamPair, connectionType, initiator, true);
+ }
+
+ @Override
+ public Map getEncounterTime() {
+ return this.encounterDate;
+ }
+
+ @Override
+ public long getTimeBeforeReconnect() {
+ return this.waitBeforeReconnect;
+ }
+
+ private void handleEncounter(StreamPair streamPair, ASAPEncounterConnectionType connectionType, boolean initiator,
+ boolean raceCondition) throws IOException {
+ // always exchange peerIDs
+ DataOutputStream dos = new DataOutputStream(streamPair.getOutputStream());
+ dos.writeUTF(this.peerID.toString());
+ DataInputStream dis = new DataInputStream(streamPair.getInputStream());
+ String remotePeerID = dis.readUTF();
+
+ if(remotePeerID != null && remotePeerID.length() > 0) {
+ streamPair.setEndpointID(remotePeerID);
+ }
+
+ CharSequence connectionID = streamPair.getEndpointID();
+ if(connectionID == null || connectionID.length() == 0) connectionID = streamPair.getSessionID();
+
+ Log.writeLog(this, this.toString(), "decide whether to pursue this new encounter: " + streamPair);
+
+ // should we connect in the first place
+ if (!this.shouldCreateConnectionToPeer(connectionID, connectionType)) {
+ // no - than shut it down.
+ Log.writeLog(this, this.toString(),
+ "close connection (on deny list or in cool down)");
+ streamPair.close();
+ return;
+ }
+
+ // new stream pair is ok. Is there a race condition expected ?
+ if(raceCondition) {
+ // avoid the nasty race condition
+ Log.writeLog(this, this.toString(), "solve race condition");
+ boolean waited = this.solveRaceCondition(streamPair, initiator, DEFAULT_WAIT_TO_AVOID_RACE_CONDITION);
+
+ // ask again?
+ if (waited) {
+ if (!this.shouldCreateConnectionToPeer(connectionID, connectionType)) {
+ streamPair.close();
+ return;
+ }
+ }
+ }
+
+ // we are through with it - remember that new stream pair
+ Log.writeLog(this, this.toString(), "remember streamPair: " + streamPair);
+ this.openStreamPairs.put(connectionID, streamPair);
+ Log.writeLog(this, this.toString(), "remember encounter: " + streamPair.getEndpointID());
+ this.encounterDate.put(streamPair.getEndpointID(), new Date());
+ try {
+ Log.writeLog(this, this.toString(), "call asap peer to handle connection");
+ ASAPConnection asapConnection =
+ this.asapConnectionHandler.handleConnection(
+ streamPair.getInputStream(), streamPair.getOutputStream(), connectionType);
+
+ asapConnection.addASAPConnectionListener(this);
+
+ Log.writeLog(this, this.toString(),
+ "asap peers is handling session: " + asapConnection.toString());
+ this.openASAPConnections.put(asapConnection, connectionID);
+
+ } catch (IOException | ASAPException e) {
+ Log.writeLog(this, this.toString(), "while launching asap connection: "
+ + e.getLocalizedMessage());
+ }
+ }
+
+ private boolean solveRaceCondition(StreamPair streamPair, boolean connectionInitiator,
+ long waitInMillis) throws IOException {
+ // run a little negotiation before we start
+ DataOutputStream dos = new DataOutputStream(streamPair.getOutputStream());
+ int remoteValue = 0;
+ String remotePeerID = null;
+
+ try {
+ // write protocol unit
+ dos.writeInt(this.randomValue);
+ dos.writeUTF(this.peerID.toString());
+
+ // read it
+ DataInputStream dis = new DataInputStream(streamPair.getInputStream());
+ remoteValue = dis.readInt();
+ remotePeerID = dis.readUTF();
+
+ if(remotePeerID != null && remotePeerID.length() > 0) streamPair.setEndpointID(remotePeerID);
+ } catch (IOException e) {
+ // decision is made - this connection is dead
+ streamPair.close();
+ }
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("try to solve race condition: random (local/remote) == ");
+ sb.append(this.randomValue);
+ sb.append("/");
+ sb.append(remoteValue);
+ sb.append(" | peerID == ");
+ sb.append(this.peerID);
+ sb.append("/");
+ sb.append(remotePeerID);
+ sb.append(" | initiator == ");
+ sb.append(connectionInitiator);
+
+ int initiatorValue, nonInitiatorValue;
+ if(connectionInitiator) {
+ initiatorValue = this.randomValue;
+ nonInitiatorValue = remoteValue;
+ } else {
+ initiatorValue = remoteValue;
+ nonInitiatorValue = this.randomValue;
+ }
+
+ sb.append(" | initiatorValue == ");
+ sb.append(initiatorValue);
+ sb.append(" | nonInitiatorValue == ");
+ sb.append(nonInitiatorValue);
+ Log.writeLog(this, this.toString(), sb.toString());
+
+ /* Here comes the bias: An initiator with a smaller value waits a moment */
+ if(connectionInitiator && initiatorValue < nonInitiatorValue) {
+ try {
+ sb = new StringBuilder();
+ sb.append("wait ");
+ sb.append(waitInMillis);
+ sb.append(" ms");
+ Log.writeLog(this, this.toString(), sb.toString());
+ Thread.sleep(waitInMillis);
+ return true; // waited
+ } catch (InterruptedException e) {
+ Log.writeLog(this, this.toString(), "wait interrupted");
+ }
+ }
+
+ return false;
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // ASAPConnectionListener //
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ @Override
+ public synchronized void asapConnectionStarted(String remotePeerName, ASAPConnection connection) {
+ CharSequence peerID = connection.getEncounteredPeer();
+ Log.writeLog(this, this.toString(), "new ASAP encounter: " + connection);
+
+ CharSequence streamPairID = this.openASAPConnections.get(connection);
+ if(PeerIDHelper.sameID(streamPairID, peerID)) {
+ // nothing to do. This connection was already established with peer id
+ return;
+ }
+
+ // connection was established with remote address. Remember that
+ Set remoteAddresses = this.peerRemoteAddresses.get(peerID);
+ if(remoteAddresses == null) {
+ remoteAddresses = new HashSet<>();
+ this.peerRemoteAddresses.put(peerID, remoteAddresses);
+ }
+
+ remoteAddresses.add(streamPairID);
+
+ }
+
+ @Override
+ public synchronized void asapConnectionTerminated(Exception terminatingException, ASAPConnection connection) {
+ Log.writeLog(this, this.toString(), "encounter terminated: " + connection);
+ CharSequence peerID = connection.getEncounteredPeer();
+
+ CharSequence peerIDOrAddress = this.openASAPConnections.get(connection);
+ this.openASAPConnections.remove(connection);
+
+ // one call will fail - who cares.
+ this.openStreamPairs.remove(peerIDOrAddress);
+ this.openStreamPairs.remove(peerID);
+
+ // was this stream pair registered with remote address? Clean peerRemoteAddress data set.
+ Set remoteAddresses = this.peerRemoteAddresses.get(peerID);
+ if(remoteAddresses != null) {
+ // this connection was registered under its remote address
+ for(CharSequence remoteAddressObject : remoteAddresses) {
+ if(PeerIDHelper.sameID(remoteAddressObject, peerIDOrAddress)) {
+ // found it
+ if(remoteAddresses.size() == 1) {
+ // remove whole entry - this was its only entry
+ this.peerRemoteAddresses.remove(peerID);
+ } else {
+ remoteAddresses.remove(remoteAddressObject);
+ }
+ // in any case - we are ready here
+ break;
+ }
+ }
+ }
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // EncounterManagerAdmin //
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ private Set denyList = new HashSet<>();
+
+ //// housekeeping deny list
+ public void clearDenyList() {
+ this.denyList = new HashSet<>();
+ try {
+ this.saveDenyList();
+ } catch (IOException | SharkException e) {
+ Log.writeLogErr(this, this.toString(), "cannot persist deny list: " + e.getLocalizedMessage());
+ }
+ }
+ private void restoreDenyList() throws SharkException, IOException {
+ if(this.extraDataStorage == null) {
+ Log.writeLog(this, this.toString(), "no persistent storage for deny list");
+ } else {
+ byte[] denyListBytes = this.extraDataStorage.getExtra(ENCOUNTER_MANAGER_DENY_LIST_KEY);
+ if(denyListBytes != null && denyListBytes.length > 0) {
+ ByteArrayInputStream bais = new ByteArrayInputStream(denyListBytes);
+ this.denyList = ASAPSerialization.readCharSequenceSetParameter(bais);
+ } else {
+ this.clearDenyList();
+ }
+ }
+ }
+
+ private void saveDenyList() throws IOException, SharkException {
+ if(this.extraDataStorage == null) {
+ Log.writeLog(this, this.toString(), "no persistent storage for deny list");
+ } else {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ASAPSerialization.writeCharSequenceSetParameter(this.denyList, baos);
+ this.extraDataStorage.putExtra(ENCOUNTER_MANAGER_DENY_LIST_KEY, baos.toByteArray());
+ }
+ }
+
+ ///// manage deny list
+ @Override
+ public void addToDenyList(CharSequence peerID) {
+ this.denyList.add(peerID);
+ try {
+ this.saveDenyList();
+ } catch (IOException | SharkException e) {
+ Log.writeLogErr(this, this.toString(), "cannot persist deny list: " + e.getLocalizedMessage());
+ }
+ }
+
+ @Override
+ public void removeFromDenyList(CharSequence peerID) {
+ this.denyList.remove(peerID);
+ try {
+ this.saveDenyList();
+ } catch (IOException | SharkException e) {
+ Log.writeLogErr(this, this.toString(), "cannot persist deny list: " + e.getLocalizedMessage());
+ }
+ }
+
+ @Override
+ public Set getDenyList() {
+ return this.denyList;
+ }
+
+ @Override
+ public Set getConnectedPeerIDs() {
+ return this.openStreamPairs.keySet();
+ }
+
+ public ASAPEncounterConnectionType getConnectionType(CharSequence peerID) throws ASAPException {
+ for(ASAPConnection connection : this.openASAPConnections.keySet()) {
+ if(PeerIDHelper.sameID(connection.getEncounteredPeer(), peerID)) {
+ // found our connection
+ return connection.getASAPEncounterConnectionType();
+ }
+ }
+ throw new ASAPException("there is no connection to peer " + peerID);
+ }
+
+ @Override
+ public void closeEncounter(CharSequence peerID) {
+ StreamPair stream2Close = this.openStreamPairs.get(peerID);
+ if(stream2Close != null) {
+ stream2Close.close();
+ }
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // utils //
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ public String toString() {
+ if(this.asapConnectionHandler != null) return this.asapConnectionHandler.toString();
+ else return "null";
+ }
+
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPEnvironmentChangesListener.java b/src/main/java/net/sharksystem/asap/ASAPEnvironmentChangesListener.java
new file mode 100644
index 0000000..eb4b52c
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPEnvironmentChangesListener.java
@@ -0,0 +1,12 @@
+package net.sharksystem.asap;
+
+import java.util.Set;
+
+public interface ASAPEnvironmentChangesListener {
+ /**
+ * ASAP peers establish connections on their own and usually if possible. This
+ * message is called if one or more connections could be established or got lost.
+ * @param peerList current list of peer we have a connection to (can be empty)
+ */
+ void onlinePeersChanged(Set peerList);
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPEnvironmentChangesListenerManagement.java b/src/main/java/net/sharksystem/asap/ASAPEnvironmentChangesListenerManagement.java
new file mode 100644
index 0000000..2d0948f
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPEnvironmentChangesListenerManagement.java
@@ -0,0 +1,15 @@
+package net.sharksystem.asap;
+
+public interface ASAPEnvironmentChangesListenerManagement {
+ /**
+ * Add listener for changes in ASAP environment
+ * @param changesListener listener which is to be added
+ */
+ void addASAPEnvironmentChangesListener(ASAPEnvironmentChangesListener changesListener);
+
+ /**
+ * Remove changes listener
+ * @param changesListener listener which is to be removed
+ */
+ void removeASAPEnvironmentChangesListener(ASAPEnvironmentChangesListener changesListener);
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPException.java b/src/main/java/net/sharksystem/asap/ASAPException.java
new file mode 100644
index 0000000..57a44cd
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPException.java
@@ -0,0 +1,20 @@
+package net.sharksystem.asap;
+
+import net.sharksystem.SharkException;
+
+/**
+ *
+ * @author thsc
+ */
+public class ASAPException extends SharkException {
+ public ASAPException() { super(); }
+ public ASAPException(String message) {
+ super(message);
+ }
+ public ASAPException(String message, Throwable cause) {
+ super(message, cause);
+ }
+ public ASAPException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPHop.java b/src/main/java/net/sharksystem/asap/ASAPHop.java
new file mode 100644
index 0000000..9559fd9
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPHop.java
@@ -0,0 +1,36 @@
+package net.sharksystem.asap;
+
+/**
+ * Describes the exchange if an ASAP message from one peer to the other
+ */
+public interface ASAPHop {
+ /**
+ * Sender is always a point-to-point sender. There is no get receiver method, though. Hops are kept in a chain.
+ * Receiver of the last entry is local peer itself. For all hops in between: Sender of next hop is receiver of
+ * the previous hop.
+ * @return
+ */
+ CharSequence sender();
+
+ /**
+ * An ASAP message exchange is based on a point-to-point connection. There are different options: Ad-hoc networks,
+ * Internet, onion networks etc. This method describes the connection type of this hop.
+ * @return
+ */
+ ASAPEncounterConnectionType getConnectionType();
+
+ /**
+ * A sender could have signed the point-to-point message transfer. This message returns true if the receiver was
+ * able to verify the signature. A false could be indicator for a forged identity or that the receiver has not got
+ * sender's public key.
+ * @return
+ */
+ boolean verified();
+
+ /**
+ * This point-to-point connection was encrypted.
+ * @return
+ */
+ boolean encrypted();
+
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPHopImpl.java b/src/main/java/net/sharksystem/asap/ASAPHopImpl.java
new file mode 100644
index 0000000..0252191
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPHopImpl.java
@@ -0,0 +1,58 @@
+package net.sharksystem.asap;
+
+public class ASAPHopImpl implements ASAPHop {
+ private final CharSequence sender;
+ private final boolean verified;
+ private final boolean encrypted;
+ private final ASAPEncounterConnectionType connectionType;
+
+ public ASAPHopImpl(CharSequence sender, boolean verified, boolean encrypted, ASAPEncounterConnectionType connectionType) {
+ this.sender = sender;
+ this.verified = verified;
+ this.encrypted = encrypted;
+ this.connectionType = connectionType;
+ }
+
+ @Override
+ public CharSequence sender() {
+ return this.sender;
+ }
+
+ @Override
+ public ASAPEncounterConnectionType getConnectionType() {
+ return this.connectionType;
+ }
+
+ @Override
+ public boolean verified() {
+ return this.verified;
+ }
+
+ @Override
+ public boolean encrypted() {
+ return this.encrypted;
+ }
+
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("sender: ");
+ sb.append(this.sender);
+ sb.append(" | ");
+ sb.append("verified: ");
+ sb.append(this.verified);
+ sb.append(" | ");
+ sb.append("encrypted: ");
+ sb.append(this.encrypted);
+ sb.append(" | ");
+ sb.append("connectionType: ");
+ switch (this.connectionType) {
+ case ONION_NETWORK: sb.append("onionNetwork"); break;
+ case ASAP_HUB: sb.append("ASAP Hub"); break;
+ case AD_HOC_LAYER_2_NETWORK: sb.append("Ad-hoc protocol"); break;
+ case INTERNET: sb.append("Internet"); break;
+ default: sb.append("unknown"); break;
+ }
+
+ return sb.toString();
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPInternalPeerWrapper.java b/src/main/java/net/sharksystem/asap/ASAPInternalPeerWrapper.java
new file mode 100644
index 0000000..d3a7eae
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPInternalPeerWrapper.java
@@ -0,0 +1,129 @@
+package net.sharksystem.asap;
+
+import net.sharksystem.SharkException;
+import net.sharksystem.asap.engine.ASAPInternalOnlinePeersChangedListener;
+import net.sharksystem.asap.engine.ASAPInternalPeer;
+import net.sharksystem.asap.protocol.ASAPConnection;
+import net.sharksystem.asap.utils.PeerIDHelper;
+import net.sharksystem.utils.Log;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Set;
+
+public abstract class ASAPInternalPeerWrapper extends ASAPListenerManagingPeer
+ implements ASAPInternalOnlinePeersChangedListener {
+
+ private ASAPInternalPeer peer;
+
+ protected void setInternalPeer(ASAPInternalPeer peer) {
+ this.peer = peer;
+ this.peer.addOnlinePeersChangedListener(this);
+
+ Log.writeLog(this, "activate online messages on that peer");
+ this.peer.activateOnlineMessages();
+ }
+
+
+ @Override
+ public boolean isASAPRoutingAllowed(CharSequence applicationFormat) throws IOException, ASAPException {
+ return this.getInternalPeer().asapRoutingAllowed(applicationFormat);
+ }
+
+ @Override
+ public void setASAPRoutingAllowed(CharSequence applicationFormat, boolean allowed)
+ throws IOException, ASAPException {
+
+ this.getInternalPeer().setAsapRoutingAllowed(applicationFormat, allowed);
+ }
+
+ protected ASAPInternalPeer getInternalPeer() {
+ return this.peer;
+ }
+
+ public CharSequence getPeerID() {
+ return this.peer.getOwner();
+ }
+
+ public boolean samePeer(ASAPPeer otherPeer) {
+ return this.samePeer(otherPeer.getPeerID());
+ }
+
+ public boolean samePeer(CharSequence otherPeerID) {
+ return PeerIDHelper.sameID(this.getPeerID(), otherPeerID);
+ }
+
+ @Override
+ public ASAPStorage getASAPStorage(CharSequence format) throws IOException, ASAPException {
+ return this.getInternalPeer().getASAPEngine(format);
+ }
+
+ public ASAPConnection handleConnection(InputStream is, OutputStream os) throws IOException, ASAPException {
+ return this.peer.handleConnection(is, os);
+ }
+
+ public ASAPConnection handleConnection(InputStream is, OutputStream os,
+ ASAPEncounterConnectionType connectionType) throws IOException, ASAPException {
+
+ return this.peer.handleConnection(is, os, connectionType);
+ }
+
+ public ASAPConnection handleConnection(InputStream is, OutputStream os, boolean encrypt, boolean sign,
+ ASAPEncounterConnectionType connectionType) throws IOException, ASAPException {
+
+ return this.peer.handleConnection(is, os, encrypt, sign, connectionType,
+ (Set)null, (Set)null);
+ }
+
+ public ASAPConnection handleConnection(
+ InputStream is, OutputStream os,
+ boolean encrypt, boolean sign,
+ Set appsWhiteList, Set appsBlackList
+ ) throws IOException, ASAPException {
+ return this.peer.handleConnection(is, os, encrypt, sign, appsWhiteList, appsBlackList);
+ }
+
+
+ public ASAPConnection handleConnection(InputStream is, OutputStream os, boolean encrypt, boolean sign,
+ ASAPEncounterConnectionType connectionType,
+ Set appsWhiteList, Set appsBlackList) throws IOException, ASAPException {
+ return this.peer.handleConnection(is, os, encrypt, sign, connectionType, appsWhiteList, appsBlackList);
+ }
+
+ @Override
+ public void notifyOnlinePeersChanged(ASAPInternalPeer peer) {
+ this.notifyOnlinePeersChanged(peer.getOnlinePeers());
+ }
+
+ public void notifyOnlinePeersChanged(Set peerList) {
+ this.environmentChangesListenerManager.notifyListeners(peerList);
+ }
+
+
+ /**
+ * Make a value persistent with key
+ * @param key
+ * @param value
+ */
+ public void putExtra(CharSequence key, byte[] value) throws IOException, ASAPException {
+ try {
+ this.peer.putExtra(key, value);
+ } catch (SharkException e) {
+ throw new ASAPException(e);
+ }
+ }
+
+ /**
+ * Return a value. Throws an exception if not set
+ * @param key
+ * @throws ASAPException key never used in putExtra
+ */
+ public byte[] getExtra(CharSequence key) throws ASAPException, IOException {
+ try {
+ return this.peer.getExtra(key);
+ } catch (SharkException e) {
+ throw new ASAPException(e);
+ }
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPListenerManagingPeer.java b/src/main/java/net/sharksystem/asap/ASAPListenerManagingPeer.java
new file mode 100644
index 0000000..e71c1ee
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPListenerManagingPeer.java
@@ -0,0 +1,55 @@
+package net.sharksystem.asap;
+
+import net.sharksystem.asap.listenermanager.ASAPChannelContentChangedListenerManager;
+import net.sharksystem.asap.listenermanager.ASAPEnvironmentChangesListenerManager;
+import net.sharksystem.asap.listenermanager.ASAPMessageReceivedListenerManager;
+
+public abstract class ASAPListenerManagingPeer implements ASAPPeer {
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // ASAPMessageReceivedListener //
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////
+ protected ASAPMessageReceivedListenerManager asapMessageReceivedListenerManager =
+ new ASAPMessageReceivedListenerManager();
+
+ public void addASAPMessageReceivedListener(CharSequence format, ASAPMessageReceivedListener listener) {
+ this.asapMessageReceivedListenerManager.addASAPMessageReceivedListener(format, listener);
+ }
+
+ @Override
+ public void removeASAPMessageReceivedListener(CharSequence format, ASAPMessageReceivedListener listener) {
+ this.asapMessageReceivedListenerManager.removeASAPMessageReceivedListener(format, listener);
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // ASAPChannelContentChangedListener //
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////
+ protected ASAPChannelContentChangedListenerManager asapChannelContentChangedListenerManager =
+ new ASAPChannelContentChangedListenerManager();
+
+ @Override
+ public void addASAPChannelContentChangedListener(CharSequence format, ASAPChannelContentChangedListener listener) {
+ this.asapChannelContentChangedListenerManager.addASAPChannelContentChangedListener(format, listener);
+ }
+
+ @Override
+ public void removeASAPChannelContentChangedListener(CharSequence format, ASAPChannelContentChangedListener listener) {
+ this.asapChannelContentChangedListenerManager.removeASAPChannelContentChangedListener(format, listener);
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // ASAPEnvironmentChangesListener //
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ protected ASAPEnvironmentChangesListenerManager environmentChangesListenerManager =
+ new ASAPEnvironmentChangesListenerManager();
+
+ @Override
+ public void addASAPEnvironmentChangesListener(ASAPEnvironmentChangesListener changesListener) {
+ this.environmentChangesListenerManager.addASAPEnvironmentChangesListener(changesListener);
+ }
+
+ @Override
+ public void removeASAPEnvironmentChangesListener(ASAPEnvironmentChangesListener changesListener) {
+ this.environmentChangesListenerManager.removeASAPEnvironmentChangesListener(changesListener);
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPMessageCompare.java b/src/main/java/net/sharksystem/asap/ASAPMessageCompare.java
new file mode 100644
index 0000000..eb81316
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPMessageCompare.java
@@ -0,0 +1,16 @@
+package net.sharksystem.asap;
+
+public interface ASAPMessageCompare {
+ /**
+ * Returns if message A is earlier than message B. This interface must be implemented
+ * by an applications and is parameter to retrieve a messages iterator object. If set, this
+ * comparision would define the order on which those messages are delivered.
+ *
+ * Note: It is always assumed that message sent / received in an earlier era are always earlier.
+ *
+ * @param messageA
+ * @param messageB
+ * @return
+ */
+ boolean earlier(byte[] messageA, byte[] messageB);
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPMessageReceivedListener.java b/src/main/java/net/sharksystem/asap/ASAPMessageReceivedListener.java
new file mode 100644
index 0000000..5b65d15
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPMessageReceivedListener.java
@@ -0,0 +1,9 @@
+package net.sharksystem.asap;
+
+import java.io.IOException;
+import java.util.List;
+
+public interface ASAPMessageReceivedListener {
+ void asapMessagesReceived(ASAPMessages messages, String senderE2E, // E2E part
+ List asapHops /* Point-to-point part */ ) throws IOException;
+}
\ No newline at end of file
diff --git a/src/main/java/net/sharksystem/asap/ASAPMessageReceivedListenerManagement.java b/src/main/java/net/sharksystem/asap/ASAPMessageReceivedListenerManagement.java
new file mode 100644
index 0000000..5cd1107
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPMessageReceivedListenerManagement.java
@@ -0,0 +1,17 @@
+package net.sharksystem.asap;
+
+public interface ASAPMessageReceivedListenerManagement {
+ /**
+ * Add a listener that is called when a message came in
+ * @param format app name == supported format
+ * @param listener listener object
+ */
+ void addASAPMessageReceivedListener(CharSequence format, ASAPMessageReceivedListener listener);
+ void removeASAPMessageReceivedListener(CharSequence format, ASAPMessageReceivedListener listener);
+
+ /**
+ * @ return number of listeners
+ * @return
+ */
+ int getNumberListener();
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPMessageSender.java b/src/main/java/net/sharksystem/asap/ASAPMessageSender.java
new file mode 100644
index 0000000..868f930
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPMessageSender.java
@@ -0,0 +1,44 @@
+package net.sharksystem.asap;
+
+import java.io.IOException;
+
+public interface ASAPMessageSender {
+ /**
+ * Send a message
+ * @param appName
+ * @param uri
+ * @param message
+ * @throws ASAPException
+ */
+ void sendASAPMessage(CharSequence appName, CharSequence uri,
+ byte[] message) throws ASAPException;
+
+ /**
+ * When calling this methode, this asap message is sent over any existing connection.
+ * It is not stored on sender or receiver side. Message listeners are called as usual. Nothing happens (no
+ * exception is thrown) if there is not a single peer encounter running.
+ * @param appName
+ * @param uri
+ * @param message
+ * @throws ASAPException
+ * @throws IOException
+ */
+ void sendTransientASAPMessage(CharSequence appName, CharSequence uri, byte[] message)
+ throws ASAPException, IOException;
+
+ /**
+ * When calling this methode, this asap message is sent over any existing connection.
+ * It is not stored on sender or receiver side. Message listeners are called as usual. Nothing happens (no
+ * exception is thrown) if there is not a single peer encounter running.
+ *
+ * @param nextHopPeerID Peer will try to send a message only to this peer. An ASAPException is thrown if there
+* is no running encounter with that peer in place.
+ * @param appName
+ * @param uri
+ * @param message
+ * @throws ASAPException
+ * @throws IOException
+ */
+ void sendTransientASAPMessage(CharSequence nextHopPeerID, CharSequence appName, CharSequence uri, byte[] message)
+ throws ASAPException, IOException;
+}
diff --git a/src/net/sharksystem/asap/apps/ASAPMessages.java b/src/main/java/net/sharksystem/asap/ASAPMessages.java
similarity index 75%
rename from src/net/sharksystem/asap/apps/ASAPMessages.java
rename to src/main/java/net/sharksystem/asap/ASAPMessages.java
index bf463c4..f2c549f 100644
--- a/src/net/sharksystem/asap/apps/ASAPMessages.java
+++ b/src/main/java/net/sharksystem/asap/ASAPMessages.java
@@ -1,9 +1,11 @@
-package net.sharksystem.asap.apps;
+package net.sharksystem.asap;
import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.engine.ASAPInternalChunk;
import java.io.IOException;
import java.util.Iterator;
+import java.util.List;
/**
* Chunks are identified by an URI and ordered by era numbers.
@@ -42,6 +44,7 @@ public interface ASAPMessages {
* first, false: newest message comes first
* @return iterator of all messages in that chunk cache
* @throws IOException
+ * @deprecated this lib works supports byte[] - apps deal with (de)serialization.
*/
Iterator getMessagesAsCharSequence() throws IOException;
@@ -63,8 +66,17 @@ public interface ASAPMessages {
* not exist
* @throws IOException couldn't read from storage
*/
- CharSequence getMessage(int position, boolean chronologically)
+ CharSequence getMessageAsCharSequence(int position, boolean chronologically)
throws ASAPException, IOException;
+ byte[] getMessage(int position, boolean chronologically)
+ throws ASAPException, IOException;
+ /**
+ * Return chunk in which message at position is to be found
+ * @param position
+ * @param chronologically
+ * @return
+ */
+ ASAPChunk getChunk(int position, boolean chronologically) throws IOException, ASAPException;
}
diff --git a/src/main/java/net/sharksystem/asap/ASAPPeer.java b/src/main/java/net/sharksystem/asap/ASAPPeer.java
new file mode 100644
index 0000000..90352a2
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPPeer.java
@@ -0,0 +1,89 @@
+package net.sharksystem.asap;
+
+import net.sharksystem.SharkException;
+import net.sharksystem.asap.crypto.ASAPKeyStore;
+import net.sharksystem.fs.ExtraData;
+
+import java.io.IOException;
+
+public interface ASAPPeer extends
+ ASAPMessageSender,
+ ASAPEnvironmentChangesListenerManagement,
+ ASAPMessageReceivedListenerManagement,
+ ASAPChannelContentChangedListenerManagement
+{
+ CharSequence UNKNOWN_USER = "anon";
+ boolean ONLINE_EXCHANGE_DEFAULT = true;
+
+ CharSequence getPeerID();
+
+ ASAPStorage getASAPStorage(CharSequence format) throws IOException, ASAPException;
+
+ /**
+ * Provide an ASAP keystore to the peer. Now, point-to-point encryption is possible.
+ * @param asapKeyStore
+ */
+ void setASAPKeyStore(ASAPKeyStore asapKeyStore);
+
+ /**
+ * Get ASAP keystore. Throws an exception if not set
+ * @return ASAP keystore
+ * @throws ASAPException if no keystore present
+ */
+ ASAPKeyStore getASAPKeyStore() throws ASAPSecurityException;
+
+ /**
+ * ASAP peer are both: application host and potential router. Routing can be switched on or off.
+ * We tend to label this behaviour with different ages (stone. bronze, internet), see discussion there.
+ *
+ * If true: This engine will route received messages
+ * @return
+ */
+ boolean isASAPRoutingAllowed(CharSequence applicationFormat) throws IOException, ASAPException;
+
+ void setASAPRoutingAllowed(CharSequence applicationFormat, boolean allowed)
+ throws IOException, ASAPException;
+
+ /**
+ * Returns true if both peer represent the same peer - ID are compared.
+ * @param otherPeer
+ * @return
+ */
+ boolean samePeer(ASAPPeer otherPeer);
+
+ boolean samePeer(CharSequence otherPeerID);
+
+ /**
+ * Handle a connection
+ * @param is
+ * @param os
+ * @param encrypt point-to-point encryption
+ * @param sign point-to-point signing / verifying ?
+ * @param connectionType
+ * @return
+ * @throws IOException
+ * @throws ASAPException
+ */
+ /*
+ ASAPConnection handleConnection(InputStream is, OutputStream os, boolean encrypt, boolean sign,
+ EncounterConnectionType connectionType) throws IOException, ASAPException;
+
+
+ */
+
+ /**
+ * Make a value persistent with key
+ * @param key
+ * @param value
+ */
+ void putExtra(CharSequence key, byte[] value) throws IOException, ASAPException;
+
+ /**
+ * Return a value. Throws an exception if not set
+ * @param key
+ * @throws ASAPException key never used in putExtra
+ */
+ byte[] getExtra(CharSequence key) throws ASAPException, IOException;
+
+ ExtraData getExtraData() throws SharkException, IOException;
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPPeerFS.java b/src/main/java/net/sharksystem/asap/ASAPPeerFS.java
new file mode 100644
index 0000000..ba4fe5d
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPPeerFS.java
@@ -0,0 +1,189 @@
+package net.sharksystem.asap;
+
+import net.sharksystem.SharkException;
+import net.sharksystem.asap.crypto.ASAPKeyStore;
+import net.sharksystem.asap.engine.*;
+import net.sharksystem.asap.utils.ASAPLogHelper;
+import net.sharksystem.fs.ExtraData;
+import net.sharksystem.utils.Log;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+public class ASAPPeerFS extends ASAPInternalPeerWrapper implements ASAPPeerService, ASAPChunkAssimilatedListener {
+ public static final CharSequence DEFAULT_ROOT_FOLDER_NAME = ASAPEngineFS.DEFAULT_ROOT_FOLDER_NAME;
+
+ private final String rootFolder;
+ private ASAPChunkAssimilatedListener chunkReceivedListener;
+
+ public ASAPPeerFS(CharSequence owner, CharSequence rootFolder,
+ Collection supportFormats) throws IOException, ASAPException {
+ super.setInternalPeer(ASAPInternalPeerFS.createASAPPeer(owner, rootFolder, supportFormats, this));
+ this.rootFolder = rootFolder.toString();
+ }
+
+ public ASAPPeerFS(CharSequence owner, CharSequence rootFolder) throws IOException, ASAPException {
+ super.setInternalPeer(ASAPInternalPeerFS.createASAPPeer(owner, rootFolder, null, this));
+ this.rootFolder = rootFolder.toString();
+ }
+
+ public void overwriteChuckReceivedListener(ASAPChunkAssimilatedListener listener) {
+ Log.writeLogErr(this, this.getPeerID(), "do not use chunk received listener - message received listener is better");
+ this.chunkReceivedListener = listener;
+ }
+
+ private void chunkAssimilated(ASAPMessages receivedMessages, CharSequence format,
+ CharSequence senderE2E, CharSequence uri, int era,
+ List asapHopList, boolean callListener) {
+
+ int nrMessages = -1;
+ try {
+ nrMessages = receivedMessages.size();
+ } catch (IOException e) {
+ // go ahead
+ }
+
+ StringBuilder sb = new StringBuilder();
+ String hopListString = "hoplist == null";
+ if(asapHopList != null) {
+ int i = 0;
+ for (ASAPHop hop : asapHopList) {
+ sb.append("hop#");
+ sb.append(i++);
+ sb.append(": ");
+ sb.append(hop.toString());
+ sb.append("\n");
+ }
+ hopListString = sb.toString();
+ }
+
+ sb = new StringBuilder();
+ sb.append("\n+++++++++++++++++++++++++++++++++++++++ chunkReceived ++++++++++++++++++++++++++++++++++++++++++++\n");
+ sb.append("E2E|P2P: " + senderE2E + " | " + asapHopList.get(asapHopList.size()-1).sender() + " | uri: " + uri);
+ sb.append(" | era: ");
+ if(era == ASAP.TRANSIENT_ERA) sb.append("transient");
+ else sb.append(era);
+ sb.append(" | app: " + format);
+ sb.append(" | #msgs: " + nrMessages);
+ sb.append("\n");
+ sb.append(hopListString);
+ sb.append("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
+ Log.writeLog(this, this.getPeerID(), sb.toString());
+
+ if(callListener) {
+ // call listener
+ String numberListeners = "null";
+ if(this.asapMessageReceivedListenerManager != null) {
+ numberListeners = String.valueOf(this.asapMessageReceivedListenerManager.getNumberListener());
+ }
+
+ Log.writeLog(this, this.getPeerID(), "notify listeners; number: " + numberListeners);
+ if (this.asapMessageReceivedListenerManager.getNumberListener() > 0) {
+ this.asapMessageReceivedListenerManager.notifyReceived(
+ format, receivedMessages, true,
+ senderE2E.toString(), asapHopList);
+ }
+
+ if (this.asapChannelContentChangedListenerManager.getNumberListener() > 0) {
+ Log.writeLog(this, this.getPeerID(),"notify channel content changed listener");
+ this.asapChannelContentChangedListenerManager.notifyChanged(format, uri, era, true);
+ }
+ }
+ }
+
+ @Override
+ public void transientMessagesReceived(ASAPMessages transientMessages, ASAPHop asapHop) throws IOException {
+ // produce hop list object
+
+ List asapHopList = new ArrayList<>();
+ asapHopList.add(asapHop);
+ this.chunkAssimilated(transientMessages,
+ transientMessages.getFormat(), asapHop.sender(), transientMessages.getURI(),
+ ASAP.TRANSIENT_ERA, asapHopList, true);
+ }
+
+ @Override
+ public void chunkStored(String format, String senderE2E, String uri, int era,
+ List asapHopList) throws IOException {
+ if(this.chunkReceivedListener != null) {
+ Log.writeLog(this, this.getPeerID(),"chunk received listener set - call this one");
+ this.chunkReceivedListener.chunkStored(format, senderE2E, uri, era, asapHopList);
+ this.chunkAssimilated(null, format, senderE2E, uri, era, asapHopList, false);
+ } else {
+ Log.writeLog(this, this.getPeerID(),"extract messages from chunk and notify listener");
+ ASAPMessages receivedMessages =
+ ASAPLogHelper.getMessagesByChunkReceivedInfos(format, senderE2E, uri, this.rootFolder, era);
+
+ this.chunkAssimilated(receivedMessages, format, senderE2E, uri, era, asapHopList, true);
+ }
+ }
+
+ /// TODO this method makes absolutely no sense in that class.
+ @Override
+ public int getNumberListener() {
+ return this.asapMessageReceivedListenerManager.getNumberListener();
+ }
+
+ // TODO move behaviour control into this package
+
+ @Override
+ public void sendASAPMessage(CharSequence appName, CharSequence uri, byte[] message) throws ASAPException {
+ try {
+ ASAPEngine engine = this.getInternalPeer().createEngineByFormat(appName);
+ engine.activateOnlineMessages(this.getInternalPeer());
+ engine.add(uri, message);
+ // send online (already done by activating online messages and adding message with engine
+ /*
+ try {
+ this.getInternalPeer().sendOnlineASAPAssimilateMessage(appName, uri, engine.getEra(), message);
+ }
+ catch(ASAPException e) {
+ // no online peers - that's ok
+ Log.writeLog(this, this.toString(), "could not send message online - that's ok.");
+ }
+ */
+ } catch (IOException e) {
+ Log.writeLog(this, this.getPeerID(),e.getLocalizedMessage());
+ throw new ASAPException("problems getting asap engine", e);
+ }
+ }
+
+ public void sendTransientASAPMessage(CharSequence appName, CharSequence uri, byte[] message)
+ throws ASAPException, IOException {
+
+ Log.writeLog(this, this.getInternalPeer().getOwner().toString(),
+ "try sending transient message over existing connections ");
+ this.getInternalPeer().sendTransientASAPAssimilateMessage(appName, uri, message);
+
+ }
+
+ public void sendTransientASAPMessage(CharSequence nextHopPeerID,
+ CharSequence appName, CharSequence uri, byte[] message) throws ASAPException, IOException {
+
+ Log.writeLog(this, this.getInternalPeer().getOwner().toString(),
+ "try sending transient message over existing connections to peerID: " + nextHopPeerID);
+ this.getInternalPeer().sendTransientASAPAssimilateMessage(appName, uri, nextHopPeerID, message);
+ }
+
+ public String toString() {
+ return this.getInternalPeer().getOwner().toString();
+ }
+
+ @Override
+ public void setASAPKeyStore(ASAPKeyStore asapKeyStore) {
+ this.getInternalPeer().setASAPKeyStore(asapKeyStore);
+ }
+
+ public ASAPKeyStore getASAPKeyStore() throws ASAPSecurityException {
+ ASAPKeyStore keyStore = this.getInternalPeer().getASAPKeyStore();
+ if(keyStore == null) throw new ASAPSecurityException("no keystore set");
+ return keyStore;
+ }
+
+ @Override
+ public ExtraData getExtraData() throws SharkException, IOException {
+ return this.getInternalPeer().getExtraData();
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPPeerService.java b/src/main/java/net/sharksystem/asap/ASAPPeerService.java
new file mode 100644
index 0000000..e1e40de
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPPeerService.java
@@ -0,0 +1,16 @@
+package net.sharksystem.asap;
+
+import net.sharksystem.asap.engine.ASAPChunkAssimilatedListener;
+
+public interface ASAPPeerService extends ASAPPeer, ASAPConnectionHandler {
+ // long DEFAULT_MAX_PROCESSING_TIME = 30000; // 30 seconds
+ long DEFAULT_MAX_PROCESSING_TIME = Long.MAX_VALUE; // eternity - debugging setting
+
+ /**
+ * Overwrite internal listener. This method is used e.g. in Androiud on service side. The asap peer is informed
+ * about newly received chunks. That news is broadcasted to application side which performs the actual processing.
+ *
+ * @param listener this listener is called instead - no further chunk processing is made by this object.
+ */
+ void overwriteChuckReceivedListener(ASAPChunkAssimilatedListener listener);
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPSecurityException.java b/src/main/java/net/sharksystem/asap/ASAPSecurityException.java
new file mode 100644
index 0000000..b66d7dd
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPSecurityException.java
@@ -0,0 +1,16 @@
+package net.sharksystem.asap;
+
+public class ASAPSecurityException extends ASAPException {
+ public ASAPSecurityException() {
+ super();
+ }
+ public ASAPSecurityException(Throwable cause) {
+ super(cause);
+ }
+ public ASAPSecurityException(String message) {
+ super(message);
+ }
+ public ASAPSecurityException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPStorage.java b/src/main/java/net/sharksystem/asap/ASAPStorage.java
new file mode 100644
index 0000000..a372f22
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPStorage.java
@@ -0,0 +1,154 @@
+package net.sharksystem.asap;
+
+import java.io.IOException;
+import java.util.List;
+
+public interface ASAPStorage {
+ /**
+ * Get owner id/name of this storage. It is the name of the local peer.
+ * @return owner id/name
+ */
+ CharSequence getOwner();
+
+ /**
+ * @return list of peers with an incoming storage
+ * @see #getExistingIncomingStorage(CharSequence)
+ */
+ List getSender();
+
+ /**
+ * Peer exchange message during an encounter. Received messages are stored in
+ * an incoming storage
+ * @param sender
+ * @return storage with received messages from a peer
+ * @throws IOException
+ * @throws ASAPException
+ */
+ ASAPStorage getExistingIncomingStorage(CharSequence sender) throws IOException, ASAPException;
+
+ /**
+ * Get storage - parameter decides if to create a non-existing storage
+ * @param sender
+ * @param create
+ * @return
+ * @throws IOException
+ * @throws ASAPException
+ */
+ ASAPStorage getIncomingStorage(CharSequence sender, boolean create) throws IOException, ASAPException;
+
+ /**
+ * Get storage - create of required
+ * @param sender
+ * @return
+ * @throws IOException
+ * @throws ASAPException
+ */
+ ASAPStorage getIncomingStorage(CharSequence sender) throws IOException, ASAPException;
+ /**
+ *
+ * @return storage format / app
+ */
+ CharSequence getFormat();
+
+ /**
+ *
+ * @return list of channel uris present in this storage
+ * @throws IOException
+ */
+ List getChannelURIs() throws IOException;
+
+ /**
+ * Create a channel that includes all messages (send or received) with this uri.
+ * @param uri
+ * @return channel containing all message issued by owner of this storage. Received messages are not part
+ * of this channel. (See makan implementation)
+ * @throws ASAPException if no channel with that uri exists in this storage
+ */
+ ASAPChannel getChannel(CharSequence uri) throws ASAPException, IOException;
+
+ /**
+ *
+ * @param uri channel uri
+ * @return if channel exists - in other words: at least one message was added with this channel uri
+ */
+ boolean channelExists(CharSequence uri) throws IOException;
+
+ /**
+ * Get oldest era available on that peer.
+ * @return
+ */
+ public int getOldestEra();
+
+ /**
+ * Get current era.
+ * @return
+ */
+ public int getEra();
+
+ /**
+ * Get next era number. Era numbers are organized in a circle. Number 0
+ * follows Integer.MAXVALUE. That method takes care of that fact.
+ * No change is made on current era.
+ *
+ * @param era
+ * @return
+ */
+ public int getNextEra(int era);
+
+ /**
+ * Get previous era number. Era numbers are organized in a circle. Er
+ * number 0 is proceeded by era number Integer.MAXVALUE.
+ * That method takes care of that fact.
+ * No change is made on current era.
+ *
+ * @param era
+ * @return
+ */
+ int getPreviousEra(int era);
+
+ /**
+ *
+ * @return The local chunk storage that is meant to be used by the local
+ * app. Note: That storage is changed during an ASAP session.
+ */
+ ASAPChunkStorage getChunkStorage();
+
+ void createChannel(CharSequence urlTarget) throws IOException, ASAPException;
+
+ void removeChannel(CharSequence uri) throws IOException;
+ /**
+ *
+ * @param uri
+ * @param messageAsBytes
+ * @throws IOException
+ * @see ASAPChannel#addMessage(byte[])
+ */
+ void add(CharSequence uri, byte[] messageAsBytes) throws IOException;
+
+ /**
+ * Put some extra information on that channel
+ * @param uri describing the channel
+ * @param key
+ * @param value
+ * @throws IOException
+ */
+ void putExtra(CharSequence uri, String key, String value) throws IOException;
+
+ /**
+ * Remove a string from extra information set
+ * @param uri
+ * @param key
+ * @return
+ * @throws IOException
+ */
+ CharSequence removeExtra(CharSequence uri, String key) throws IOException;
+
+ /**
+ * Get a string from extra information set without removing
+ * @param uri
+ * @param key
+ * @return
+ * @throws IOException
+ */
+ CharSequence getExtra(CharSequence uri, String key) throws IOException;
+}
diff --git a/src/main/java/net/sharksystem/asap/ASAPUtils.java b/src/main/java/net/sharksystem/asap/ASAPUtils.java
new file mode 100644
index 0000000..26b00ce
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/ASAPUtils.java
@@ -0,0 +1,39 @@
+package net.sharksystem.asap;
+
+import net.sharksystem.utils.Log;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+public class ASAPUtils {
+ /**
+ *
+ * @param searchSpace list of possible eras
+ * @param fromEra lowest era
+ * @param toEra highest era
+ * @return list of era which are within from and to and also in search space
+ */
+ public static Collection getErasInRange(Collection searchSpace,
+ int fromEra, int toEra) {
+
+ Collection eras = new ArrayList<>();
+
+ // the only trick is to be aware of the cyclic nature of era numbers
+ boolean wrapped = fromEra > toEra; // it reached the era end and started new
+
+ for(Integer era : searchSpace) {
+ if(!wrapped) {
+ //INIT ---- from-> +++++++++++++ <-to ----- MAX (+ fits)
+ if(era >= fromEra && era <= toEra) eras.add(era);
+ } else {
+ // INIT+++++++++<-to ------ from->++++++MAX
+ if(era <= toEra && era >= ASAP.INITIAL_ERA
+ || era >= fromEra && era <= ASAP.MAX_ERA
+ ) eras.add(era);
+ }
+ }
+
+ return eras;
+
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/apps/TCPServerSocketAcceptor.java b/src/main/java/net/sharksystem/asap/apps/TCPServerSocketAcceptor.java
new file mode 100644
index 0000000..8703b34
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/apps/TCPServerSocketAcceptor.java
@@ -0,0 +1,43 @@
+package net.sharksystem.asap.apps;
+
+import net.sharksystem.asap.ASAPEncounterManager;
+import net.sharksystem.asap.ASAPEncounterConnectionType;
+import net.sharksystem.utils.Log;
+import net.sharksystem.utils.streams.StreamPair;
+import net.sharksystem.utils.tcp.SocketFactory;
+import net.sharksystem.utils.tcp.StreamPairCreatedListener;
+
+import java.io.IOException;
+
+public class TCPServerSocketAcceptor implements StreamPairCreatedListener {
+ private final ASAPEncounterManager encounterManager;
+ private final SocketFactory socketFactory;
+
+ public TCPServerSocketAcceptor(int portNumber, ASAPEncounterManager encounterManager, boolean remainOpen)
+ throws IOException {
+ this.encounterManager = encounterManager;
+ this.socketFactory = new SocketFactory(portNumber, this, remainOpen);
+
+ Log.writeLog(this, "start socket factory - no race condition assumed");
+ new Thread(socketFactory).start();
+ }
+
+ public TCPServerSocketAcceptor(int portNumber, ASAPEncounterManager encounterManager) throws IOException {
+ this(portNumber, encounterManager, false);
+ }
+
+ public void close() throws IOException {
+ this.socketFactory.close();
+ }
+
+ @Override
+ public void streamPairCreated(StreamPair streamPair) {
+ Log.writeLog(this, "new stream pair created");
+ try {
+ this.encounterManager.handleEncounter(streamPair, ASAPEncounterConnectionType.INTERNET);
+ } catch (IOException e) {
+ Log.writeLogErr(this, "exception when asking for new connection handling: "
+ + e.getLocalizedMessage());
+ }
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/apps/gossip/GossipUI.java b/src/main/java/net/sharksystem/asap/apps/gossip/GossipUI.java
new file mode 100644
index 0000000..4b386aa
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/apps/gossip/GossipUI.java
@@ -0,0 +1,164 @@
+package net.sharksystem.asap.apps.gossip;
+
+import net.sharksystem.asap.ASAPHop;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPMessages;
+import net.sharksystem.asap.engine.*;
+import net.sharksystem.asap.utils.ASAPLogHelper;
+import net.sharksystem.asap.cmdline.TCPStream;
+import net.sharksystem.asap.cmdline.TCPStreamCreatedListener;
+import net.sharksystem.utils.Log;
+import net.sharksystem.utils.SerializationHelper;
+
+import java.io.IOException;
+import java.text.DateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+// java -cp ASAP_Engine_x.y.z.jar net.sharksystem.asap.apps.gossip.GossipUI Alice 7070 7071
+public class GossipUI implements ASAPChunkAssimilatedListener {
+ private List remotePortNumber;
+ private String peerName;
+ private int portnumber;
+ private ASAPInternalPeer asapInternalPeer;
+ private String rootFolderName;
+
+ public GossipUI(String peerName, int portnumber, List portnumberlist) {
+ this.peerName = peerName;
+ this.portnumber = portnumber;
+ this.remotePortNumber = portnumberlist;
+
+ Log.writeLog(this, "start peer " + this.peerName);
+ Log.writeLog(this, "local port " + this.portnumber);
+ Log.writeLog(this, "try to connect to ports " + this.remotePortNumber);
+ }
+
+ public static void main(String args[]) throws InterruptedException {
+ if(args.length < 3) {
+ Log.writeLogErr(GossipUI.class, "Peer name, local port and least one port required to establish a network");
+ System.exit(0);
+ }
+
+ // parse and set up
+ String peerName = args[0];
+ int portnumber = Integer.parseInt(args[1]);
+ List portnumberlist = new ArrayList<>();
+ for(int i = 2; i < args.length; i++) {
+ portnumberlist.add(Integer.parseInt(args[i]));
+ }
+
+ GossipUI gossip = new GossipUI(peerName, portnumber, portnumberlist);
+
+ gossip.go();
+
+ // wait forever
+ Thread.sleep(10000);
+ }
+
+ private void println(String msg) {
+ Log.writeLog(this, "///////////////////////////////////////////////////");
+ Log.writeLog(this, "Example: " + msg);
+ Log.writeLog(this, "///////////////////////////////////////////////////");
+ }
+
+ private void go() {
+ try {
+ this.println("set up system");
+ this.rootFolderName = this.peerName;
+ this.asapInternalPeer = ASAPInternalPeerFS.createASAPPeer(this.peerName,
+ this.rootFolderName, ASAPInternalPeer.DEFAULT_MAX_PROCESSING_TIME, this);
+
+ this.println("create engine");
+ ASAPEngine exampleApp = asapInternalPeer.createEngineByFormat("exampleApp");
+
+ DateFormat df = DateFormat.getInstance();
+ String myMessage = "message from " + this.peerName + " at " + df.format(new Date());
+
+ // convert to bytes
+ byte[] byteMessage = SerializationHelper.str2bytes(myMessage);
+ this.println("add message");
+ exampleApp.add("exampleChannel", byteMessage);
+
+ this.println("open tcp server port");
+ // try to establish connections
+ new ASAPConnectionCreator(new TCPStream(this.portnumber, true,
+ "server port: " + this.peerName));
+
+ this.println("try to connect others");
+ for(int port : this.remotePortNumber) {
+ new ASAPConnectionCreator(port);
+ }
+
+ } catch (ASAPException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void chunkStored(String format, String senderE2E, String uri, int era,
+ List asapHop) throws IOException {
+
+ ASAPMessages receivedMessages =
+ ASAPLogHelper.getMessagesByChunkReceivedInfos(format, senderE2E, uri, this.rootFolderName, era);
+
+ this.println("messages received: " + format + " | " + senderE2E + " | " + uri);
+
+ Iterator messages = receivedMessages.getMessages();
+ while(messages.hasNext()) {
+ byte[] msgBytes = messages.next();
+ String receivedMessage = SerializationHelper.bytes2str(msgBytes);
+ this.println("message received: " + receivedMessage);
+ };
+ }
+
+ private void printReceivedMessages(ASAPMessages asapMessages, List asapHop) throws IOException {
+ this.println("messages received: " + asapMessages.getFormat() + " | " + asapMessages.getURI());
+
+ Iterator messages = asapMessages.getMessages();
+ while(messages.hasNext()) {
+ byte[] msgBytes = messages.next();
+ String receivedMessage = SerializationHelper.bytes2str(msgBytes);
+ this.println("message received: " + receivedMessage);
+ };
+ }
+
+ public void transientMessagesReceived(ASAPMessages transientMessages, ASAPHop asapHop) throws IOException {
+ this.printReceivedMessages(transientMessages, null);
+ }
+
+ private class ASAPConnectionCreator extends Thread implements TCPStreamCreatedListener {
+ private TCPStream tcpStream;
+
+ ASAPConnectionCreator(int port) {
+ this(new TCPStream(port, false, "connect to " + String.valueOf(port)));
+ }
+
+ ASAPConnectionCreator(TCPStream tcpStream) {
+ this.tcpStream = tcpStream;
+ this.tcpStream.setListener(ASAPConnectionCreator.this);
+ this.start();
+ }
+
+ public void run() {
+ try {
+ this.tcpStream.start();
+ this.tcpStream.waitForConnection(Long.MAX_VALUE);
+ } catch (IOException e) {
+ println("wait for connection killed. ");
+ }
+ }
+
+ @Override
+ public void streamCreated(TCPStream channel) {
+ try {
+ GossipUI.this.asapInternalPeer.handleConnection(channel.getInputStream(), channel.getOutputStream());
+ } catch (Exception e) {
+ GossipUI.this.println("exception caught: " + e.getLocalizedMessage());
+ }
+ }
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/apps/testsupport/ASAPTestPeerFS.java b/src/main/java/net/sharksystem/asap/apps/testsupport/ASAPTestPeerFS.java
new file mode 100644
index 0000000..a7be174
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/apps/testsupport/ASAPTestPeerFS.java
@@ -0,0 +1,77 @@
+package net.sharksystem.asap.apps.testsupport;
+
+import net.sharksystem.asap.ASAPPeerFS;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPEncounterConnectionType;
+import net.sharksystem.testhelper.ASAPTesthelper;
+import net.sharksystem.utils.Log;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.Collection;
+
+public class ASAPTestPeerFS extends ASAPPeerFS {
+ private ServerSocket serverSocket = null;
+ private Socket socket = null;
+
+ public ASAPTestPeerFS(CharSequence peerName, Collection supportedFormats) throws IOException, ASAPException {
+ this(peerName, "./testPeerFS/" + peerName, supportedFormats);
+ }
+
+ public ASAPTestPeerFS(CharSequence peerName, CharSequence rootFolder, Collection supportedFormats)
+ throws IOException, ASAPException {
+ super(peerName, rootFolder, supportedFormats);
+ }
+
+ public void startEncounter(int port, ASAPTestPeerFS otherPeer) throws IOException {
+ this.serverSocket = new ServerSocket(port);
+
+ new Thread(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ ASAPTestPeerFS.this.socket = ASAPTestPeerFS.this.serverSocket.accept();
+ } catch (IOException e) {
+ Log.writeLog(ASAPTestPeerFS.this,"fatal while waiting for client to connect: "
+ + e.getLocalizedMessage());
+ }
+
+ ASAPTestPeerFS.this.startSession();
+ }
+ }).start();
+
+ // wait a moment
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ }
+
+ otherPeer.connect(port);
+ }
+
+ private void connect(int port) throws IOException {
+ this.socket = new Socket("localhost", port);
+ this.startSession();
+ }
+
+ public void stopEncounter(ASAPTestPeerFS otherPeer) throws IOException {
+ this.socket.close();
+ }
+
+ private void startSession() {
+ new Thread(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ ASAPTestPeerFS.this.handleConnection(
+ ASAPTestPeerFS.this.socket.getInputStream(),
+ ASAPTestPeerFS.this.socket.getOutputStream(),
+ ASAPEncounterConnectionType.INTERNET);
+ } catch (IOException | ASAPException e) {
+ Log.writeLog(ASAPTestPeerFS.this,"fatal while connecting: " + e.getLocalizedMessage());
+ }
+ }
+ }).start();
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/apps/testsupport/TestASAPConnectionHandler.java b/src/main/java/net/sharksystem/asap/apps/testsupport/TestASAPConnectionHandler.java
new file mode 100644
index 0000000..d850afa
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/apps/testsupport/TestASAPConnectionHandler.java
@@ -0,0 +1,81 @@
+package net.sharksystem.asap.apps.testsupport;
+
+import net.sharksystem.asap.ASAPConnectionHandler;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPEncounterConnectionType;
+import net.sharksystem.asap.protocol.ASAPConnection;
+import net.sharksystem.asap.protocol.ASAPConnectionListener;
+import net.sharksystem.asap.protocol.ASAPOnlineMessageSource;
+import net.sharksystem.utils.Log;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Set;
+
+public class TestASAPConnectionHandler implements ASAPConnectionHandler {
+ @Override
+ public ASAPConnection handleConnection(InputStream is, OutputStream os, boolean encrypt, boolean sign, Set appsWhiteList, Set appsBlackList) throws IOException, ASAPException {
+ return this.dummyHandleConnection();
+ }
+
+ @Override
+ public ASAPConnection handleConnection(InputStream is, OutputStream os, boolean encrypt, boolean sign, ASAPEncounterConnectionType connectionType, Set appsWhiteList, Set appsBlackList) throws IOException, ASAPException {
+ return this.dummyHandleConnection();
+ }
+
+ @Override
+ public ASAPConnection handleConnection(InputStream is, OutputStream os) throws IOException, ASAPException {
+ return this.dummyHandleConnection();
+ }
+
+ @Override
+ public ASAPConnection handleConnection(InputStream inputStream, OutputStream outputStream, ASAPEncounterConnectionType connectionType) throws IOException, ASAPException {
+ return this.dummyHandleConnection();
+ }
+
+ private ASAPConnection dummyHandleConnection() {
+ Log.writeLog(this, "handleConnection");
+ return new ASAPConnection() {
+ @Override
+ public CharSequence getEncounteredPeer() {
+ return "dummy";
+ }
+
+ @Override
+ public void addOnlineMessageSource(ASAPOnlineMessageSource source) {
+
+ }
+
+ @Override
+ public void removeOnlineMessageSource(ASAPOnlineMessageSource source) {
+
+ }
+
+ @Override
+ public void addASAPConnectionListener(ASAPConnectionListener asapConnectionListener) {
+
+ }
+
+ @Override
+ public void removeASAPConnectionListener(ASAPConnectionListener asapConnectionListener) {
+
+ }
+
+ @Override
+ public boolean isSigned() {
+ return false;
+ }
+
+ @Override
+ public ASAPEncounterConnectionType getASAPEncounterConnectionType() {
+ return ASAPEncounterConnectionType.UNKNOWN;
+ }
+
+ @Override
+ public void kill() {
+
+ }
+ };
+ }
+}
diff --git a/src/net/sharksystem/cmdline/CmdLineUI.java b/src/main/java/net/sharksystem/asap/cmdline/CmdLineUI.java
similarity index 53%
rename from src/net/sharksystem/cmdline/CmdLineUI.java
rename to src/main/java/net/sharksystem/asap/cmdline/CmdLineUI.java
index 50cc969..5bdeb27 100644
--- a/src/net/sharksystem/cmdline/CmdLineUI.java
+++ b/src/main/java/net/sharksystem/asap/cmdline/CmdLineUI.java
@@ -1,7 +1,10 @@
-package net.sharksystem.cmdline;
+package net.sharksystem.asap.cmdline;
-import net.sharksystem.asap.*;
-import net.sharksystem.asap.protocol.ASAP_1_0;
+import net.sharksystem.asap.ASAPChannel;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.engine.ASAPInternalStorage;
+import net.sharksystem.asap.engine.*;
+import net.sharksystem.fs.FSUtils;
import java.io.*;
import java.util.*;
@@ -17,27 +20,27 @@ public class CmdLineUI {
public static final String LIST = "list";
public static final String KILL = "kill";
public static final String SETWAITING = "setwaiting";
- public static final String CREATE_ASAP_ENGINE = "newengine";
+ public static final String CREATE_ASAP_PEER = "newpeer";
public static final String CREATE_ASAP_APP = "newapp";
public static final String CREATE_ASAP_CHANNEL = "newchannel";
public static final String CREATE_ASAP_MESSAGE = "newmessage";
public static final String RESET_ASAP_STORAGES = "resetstorage";
- public static final String SET_SEND_RECEIVED_MESSAGES = "sendReceived";
+ public static final String SET_SEND_RECEIVED_MESSAGES = "setSendReceived";
public static final String PRINT_CHANNEL_INFORMATION = "printChannelInfo";
public static final String PRINT_STORAGE_INFORMATION = "printStorageInfo";
public static final String PRINT_ALL_INFORMATION = "printAll";
+ public static final String SLEEP = "sleep";
+ public static final String SHOW_LOG = "showlog";
- private final PrintStream consoleOutput;
- private final BufferedReader userInput;
+ private PrintStream standardOut = System.out;
+ private PrintStream standardError = System.err;
- public static final String TESTS_ROOT_FOLDER = "tests";
- private Map engines = new HashMap();
- private String getStorageKey(String owner, String appName) {
- return owner + ":" + appName;
- }
- private Map storages = new HashMap();
+ private BufferedReader userInput;
+
+ public static final String PEERS_ROOT_FOLDER = "asapPeers";
+ private Map peers = new HashMap();
- public static void main(String[] args) {
+ public static void main(String[] args) throws IOException, ASAPException {
PrintStream os = System.out;
os.println("Welcome SN2 version 0.1");
@@ -47,14 +50,39 @@ public static void main(String[] args) {
userCmd.runCommandLoop();
}
- public CmdLineUI(PrintStream os, InputStream is) {
- this.consoleOutput = os;
- this.userInput = new BufferedReader(new InputStreamReader(is));
+ public CmdLineUI(PrintStream out) throws IOException, ASAPException {
+ this(out, null);
+ }
+
+ public void setOutStreams(PrintStream ps) {
+ this.standardOut = ps;
+ this.standardError = ps;
+ }
+
+ /**
+ * only for batch processing - removes anything from the past
+ * @throws IOException
+ * @throws ASAPException
+ */
+ public CmdLineUI() {
+ this.doResetASAPStorages();
}
- public CmdLineUI(PrintStream out) {
- this.consoleOutput = out;
- this.userInput = null;
+ public CmdLineUI(PrintStream os, InputStream is) throws IOException, ASAPException {
+ this.standardOut = os;
+ this.userInput = is != null ? new BufferedReader(new InputStreamReader(is)) : null;
+
+ // set up peers
+ File rootFolder = new File(PEERS_ROOT_FOLDER);
+ if(rootFolder.exists()) {
+ // each root folder is a peer - per definition in this very application
+ String[] peerNames = rootFolder.list();
+
+ // set up peers
+ for(String peerName : peerNames) {
+ this.createPeer(peerName);
+ }
+ }
}
public void printUsage() {
@@ -79,26 +107,26 @@ public void printUsage() {
b.append(SETWAITING);
b.append(".. set waiting period");
b.append("\n");
- b.append(CREATE_ASAP_ENGINE);
- b.append(".. create new asap engine");
+ b.append(CREATE_ASAP_PEER);
+ b.append(".. create new asap peer");
b.append("\n");
b.append(CREATE_ASAP_APP);
- b.append(".. create new asap app (==storage)");
+ b.append(".. create new asap app (==engine)");
b.append("\n");
b.append(CREATE_ASAP_CHANNEL);
b.append(".. create new closed asap channel");
b.append("\n");
b.append(CREATE_ASAP_MESSAGE);
- b.append(".. add message to storage");
+ b.append(".. add message to engine");
b.append("\n");
b.append(RESET_ASAP_STORAGES);
- b.append(".. removes all asap storages");
+ b.append(".. removes all asap engines");
b.append("\n");
b.append(SET_SEND_RECEIVED_MESSAGES);
b.append(".. set whether received message are to be sent");
b.append("\n");
b.append(PRINT_ALL_INFORMATION);
- b.append(".. print general information of all storages of a user");
+ b.append(".. print general information of peers");
b.append("\n");
b.append(PRINT_STORAGE_INFORMATION);
b.append(".. print general information about a storage");
@@ -106,25 +134,32 @@ public void printUsage() {
b.append(PRINT_CHANNEL_INFORMATION);
b.append(".. print general information about a channel");
b.append("\n");
+ b.append(SLEEP);
+ b.append(".. sleep some milliseconds - helps writing batch programs");
+ b.append("\n");
+ b.append(SHOW_LOG);
+ b.append(".. print log of entered commands of this session");
+ b.append("\n");
b.append(EXIT);
b.append(".. exit");
- this.consoleOutput.println(b.toString());
+ this.standardOut.println(b.toString());
}
- public void printUsage(String cmdString, String comment) {
- PrintStream out = this.consoleOutput;
+ public void printUsage(String cmdString, String comment) throws ASAPException {
+ PrintStream out = this.standardOut;
if(comment == null) comment = " ";
out.println("malformed command: " + comment);
out.println("use:");
switch(cmdString) {
case CONNECT:
- out.println(CONNECT + " [IP/DNS-Name_remoteHost] remotePort engineName");
+ out.println(CONNECT + " [IP/DNS-Name_remoteHost] remotePort localEngineName");
out.println("omitting remote host: localhost is assumed");
out.println("example: " + CONNECT + " localhost 7070 Bob");
out.println("example: " + CONNECT + " 7070 Bob");
- out.println("in both cases try to connect to localhost:7070 and let engine Bob handle connection when established");
+ out.println("in both cases try to connect to localhost:7070 and let engine Bob handle " +
+ "connection when established");
break;
case OPEN:
out.println(OPEN + " localPort engineName");
@@ -139,28 +174,29 @@ public void printUsage(String cmdString, String comment) {
out.println("example: " + KILL + " localhost:7070");
out.println("kills channel named localhost:7070");
out.println("channel names are produced by using list");
- out.println(KILL + "all .. kills all open connections");
+ out.println(KILL + " all .. kills all open connections");
break;
case SETWAITING:
out.println(SETWAITING + " number of millis to wait between two connection attempts");
out.println("example: " + KILL + " 1000");
out.println("set waiting period to one second");
break;
- case CREATE_ASAP_ENGINE:
- out.println(CREATE_ASAP_ENGINE + " name");
- out.println("example: " + CREATE_ASAP_ENGINE + " Alice");
- out.println("create engine called Alice - data kept under a folder called tests/Alice");
+ case CREATE_ASAP_PEER:
+ out.println(CREATE_ASAP_PEER + " name");
+ out.println("example: " + CREATE_ASAP_PEER + " Alice");
+ out.println("create peer called Alice - data kept under a folder called "
+ + PEERS_ROOT_FOLDER + "/Alice");
break;
case CREATE_ASAP_APP:
- out.println(CREATE_ASAP_APP + " owner appName");
+ out.println(CREATE_ASAP_APP + " peername appName");
out.println("example: " + CREATE_ASAP_APP + " Alice chat");
break;
case CREATE_ASAP_CHANNEL:
- out.println(CREATE_ASAP_CHANNEL + " owner appName uri (recipient)+");
+ out.println(CREATE_ASAP_CHANNEL + " peername appName uri (recipient)+");
out.println("example: " + CREATE_ASAP_CHANNEL + " Alice chat sn2://abChat Bob Clara");
break;
case CREATE_ASAP_MESSAGE:
- out.println(CREATE_ASAP_MESSAGE + " owner appName uri message");
+ out.println(CREATE_ASAP_MESSAGE + " peername appName uri message");
out.println("example: " + CREATE_ASAP_MESSAGE + " Alice chat sn2://abChat HiBob");
out.println("note: message can only be ONE string. That would not work:");
out.println("does not work: " + CREATE_ASAP_MESSAGE + " Alice chat sn2://abChat Hi Bob");
@@ -176,30 +212,49 @@ public void printUsage(String cmdString, String comment) {
out.println("example: " + SET_SEND_RECEIVED_MESSAGES + " Alice:chat on");
break;
case PRINT_CHANNEL_INFORMATION:
- out.println(PRINT_CHANNEL_INFORMATION + " user appName uri");
+ out.println(PRINT_CHANNEL_INFORMATION + " peername appName uri");
out.println("example: " + PRINT_CHANNEL_INFORMATION + " Alice chat sn2://abChat");
break;
case PRINT_STORAGE_INFORMATION:
- out.println(PRINT_STORAGE_INFORMATION + " user appName");
+ out.println(PRINT_STORAGE_INFORMATION + " peername appName");
out.println("example: " + PRINT_STORAGE_INFORMATION + " Alice chat");
break;
case PRINT_ALL_INFORMATION:
- out.println(PRINT_ALL_INFORMATION + "user");
- out.println("example: " + PRINT_ALL_INFORMATION + " Alice ");
+ out.println(PRINT_ALL_INFORMATION);
+ break;
+ case SLEEP:
+ out.println(SLEEP + " milliseconds");
+ out.println("example: " + SLEEP + " sleep 1000");
+ out.println("process sleeps a second == 1000 ms");
+ break;
+ case SHOW_LOG:
+ out.println(SHOW_LOG);
break;
default:
out.println("unknown command: " + cmdString);
}
+ throw new ASAPException("had to print usage");
}
- public void runCommandLoop() {
+ private List cmds = new ArrayList<>();
+ public void runCommandLoop(PrintStream os, InputStream is) {
+ this.standardOut = os;
+ this.userInput = is != null ? new BufferedReader(new InputStreamReader(is)) : null;
+
+ this.runCommandLoop();
+ }
+
+ public void runCommandLoop() {
boolean again = true;
+
while(again) {
+ boolean rememberCommand = true;
+ String cmdLineString = null;
try {
// read user input
- String cmdLineString = userInput.readLine();
+ cmdLineString = userInput.readLine();
// finish that loop if less than nothing came in
if(cmdLineString == null) break;
@@ -230,8 +285,8 @@ public void runCommandLoop() {
this.doKill(parameterString); break;
case SETWAITING:
this.doSetWaiting(parameterString); break;
- case CREATE_ASAP_ENGINE:
- this.doCreateASAPMultiEngine(parameterString); break;
+ case CREATE_ASAP_PEER:
+ this.doCreateASAPPeer(parameterString); break;
case CREATE_ASAP_APP: // same
this.doCreateASAPApp(parameterString); break;
case CREATE_ASAP_CHANNEL:
@@ -246,55 +301,115 @@ public void runCommandLoop() {
this.doPrintChannelInformation(parameterString); break;
case PRINT_STORAGE_INFORMATION:
this.doPrintStorageInformation(parameterString); break;
+ case SLEEP:
+ this.doSleep(parameterString); break;
+ case SHOW_LOG:
+ this.doShowLog(); rememberCommand = false; break;
case PRINT_ALL_INFORMATION:
- this.doPrintAllInformation(parameterString); break;
+ this.doPrintAllInformation(); break;
case "q": // convenience
case EXIT:
this.doKill("all");
again = false; break; // end loop
- default: this.consoleOutput.println("unknown command:" +
- cmdLineString);
+ default: this.standardError.println("unknown command:" + cmdLineString);
this.printUsage();
+ rememberCommand = false;
break;
}
+ } catch (ASAPException ex) {
+ rememberCommand = false;
} catch (IOException ex) {
- this.consoleOutput.println("cannot read from input stream");
+ this.standardOut.println("cannot read from input stream");
System.exit(0);
}
+
+ if(rememberCommand) {
+ this.cmds.add(cmdLineString);
+ }
}
}
- private Map channels = new HashMap<>();
+ private Map streams = new HashMap<>();
private long waitPeriod = 1000*30; // 30 seconds
private void setWaitPeriod(long period) {
this.waitPeriod = period;
}
- private MultiASAPEngineFS getMultiEngine(String engineName) throws ASAPException {
- MultiASAPEngineFS multiASAPEngineFS = this.engines.get(engineName);
- if(multiASAPEngineFS == null) {
- throw new ASAPException("engine does not exist: " + engineName);
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // ASAP API usage //
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ private void createPeer(String name) throws IOException, ASAPException {
+ ExampleASAPChunkReceivedListener asapChunkReceivedListener =
+ new ExampleASAPChunkReceivedListener(PEERS_ROOT_FOLDER + "/" + name);
+
+ ASAPInternalPeer asapInternalPeer = ASAPInternalPeerFS.createASAPPeer(name, // peer name
+ PEERS_ROOT_FOLDER + "/" + name, // peer folder
+ asapChunkReceivedListener);
+
+ this.peers.put(name, asapInternalPeer);
+ }
+
+ private ASAPEngine getEngine(String peername, String appName) throws ASAPException, IOException {
+ ASAPInternalPeer asapInternalPeer = this.peers.get(peername);
+ if(asapInternalPeer == null) {
+ throw new ASAPException("peer does not exist: " + peername);
}
- return multiASAPEngineFS;
+ return asapInternalPeer.getEngineByFormat(appName);
+ }
+
+ public ASAPInternalPeer getASAPPeer(String peerName) throws ASAPException {
+ ASAPInternalPeer asapInternalPeer = this.peers.get(peerName);
+ if(asapInternalPeer == null) {
+ throw new ASAPException("engine does not exist: " + peerName);
+ }
+
+ return asapInternalPeer;
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // attach layer 2 (ad-hoc) protocol to ASAP //
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ private void startTCPStream(String name, TCPStream stream, String peerName) throws ASAPException {
+ stream.setWaitPeriod(this.waitPeriod);
+ ASAPInternalPeer asapInternalPeer = this.getASAPPeer(peerName);
+
+ stream.setListener(new TCPStreamCreatedHandler(asapInternalPeer));
+ stream.start();
+ this.streams.put(name, stream);
}
- private void startChannel(String name, TCPChannel channel, String engineName) throws ASAPException {
- channel.setWaitPeriod(this.waitPeriod);
- MultiASAPEngineFS multiASAPEngineFS = this.getMultiEngine(engineName);
+ private class TCPStreamCreatedHandler implements TCPStreamCreatedListener {
+ private final ASAPInternalPeer asapInternalPeer;
- channel.setListener(new TCPChannelCreatedHandler(multiASAPEngineFS));
- channel.start();
- this.channels.put(name, channel);
+ public TCPStreamCreatedHandler(ASAPInternalPeer asapInternalPeer) {
+ this.asapInternalPeer = asapInternalPeer;
+ }
+
+ @Override
+ public void streamCreated(TCPStream channel) {
+ CmdLineUI.this.standardOut.println("Channel created");
+
+ try {
+ this.asapInternalPeer.handleConnection(
+ channel.getInputStream(),
+ channel.getOutputStream());
+ } catch (IOException | ASAPException e) {
+ CmdLineUI.this.standardOut.println("call of engine.handleConnection failed: "
+ + e.getLocalizedMessage());
+ }
+ }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
// method implementations //
////////////////////////////////////////////////////////////////////////////////////////////////////////
- public void doConnect(String parameterString) {
+ public void doConnect(String parameterString) throws ASAPException {
StringTokenizer st = new StringTokenizer(parameterString);
try {
@@ -313,7 +428,7 @@ public void doConnect(String parameterString) {
String name = remoteHost + ":" + remotePortString;
- this.startChannel(name, new TCPChannel(remotePort, false, name), engineName);
+ this.startTCPStream(name, new TCPStream(remotePort, false, name), engineName);
}
catch(RuntimeException re) {
this.printUsage(CONNECT, re.getLocalizedMessage());
@@ -322,7 +437,7 @@ public void doConnect(String parameterString) {
}
}
- public void doOpen(String parameterString) {
+ public void doOpen(String parameterString) throws ASAPException {
StringTokenizer st = new StringTokenizer(parameterString);
try {
@@ -332,7 +447,7 @@ public void doOpen(String parameterString) {
int port = Integer.parseInt(portString);
String name = "server:" + port;
- this.startChannel(name, new TCPChannel(port, true, name), engineName);
+ this.startTCPStream(name, new TCPStream(port, true, name), engineName);
}
catch(RuntimeException re) {
this.printUsage(OPEN, re.getLocalizedMessage());
@@ -341,44 +456,38 @@ public void doOpen(String parameterString) {
}
}
- public void doList() {
- System.out.println("connections:");
- for(String connectionName : this.channels.keySet()) {
- System.out.println(connectionName);
- }
- System.out.println("storages:");
- for(String storageName : this.storages.keySet()) {
- System.out.println(storageName);
- }
- System.out.println("engines:");
- for(String engineName : this.engines.keySet()) {
- System.out.println(engineName);
+ public void doList() throws ASAPException {
+ this.standardOut.println("connections:");
+ for(String connectionName : this.streams.keySet()) {
+ this.standardOut.println(connectionName);
}
+
+ this.doPrintAllInformation();
}
- public void doKill(String parameterString) {
+ public void doKill(String parameterString) throws ASAPException {
StringTokenizer st = new StringTokenizer(parameterString);
try {
String channelName = st.nextToken();
if(channelName.equalsIgnoreCase("all")) {
- System.out.println("kill all open channels..");
- for(TCPChannel channel : this.channels.values()) {
+ this.standardOut.println("kill all open channels..");
+ for(TCPStream channel : this.streams.values()) {
channel.kill();
}
- this.channels = new HashMap<>();
- System.out.println(".. done");
+ this.streams = new HashMap<>();
+ this.standardOut.println(".. done");
} else {
- TCPChannel channel = this.channels.remove(channelName);
+ TCPStream channel = this.streams.remove(channelName);
if (channel == null) {
- System.err.println("channel does not exist: " + channelName);
+ this.standardError.println("channel does not exist: " + channelName);
return;
}
- System.out.println("kill channel");
+ this.standardOut.println("kill channel");
channel.kill();
- System.out.println(".. done");
+ this.standardOut.println(".. done");
}
}
catch(RuntimeException e) {
@@ -386,7 +495,7 @@ public void doKill(String parameterString) {
}
}
- public void doSetWaiting(String parameterString) {
+ public void doSetWaiting(String parameterString) throws ASAPException {
StringTokenizer st = new StringTokenizer(parameterString);
try {
@@ -399,41 +508,37 @@ public void doSetWaiting(String parameterString) {
}
}
- public void doCreateASAPMultiEngine(String parameterString) {
+ public void doCreateASAPPeer(String parameterString) throws ASAPException {
StringTokenizer st = new StringTokenizer(parameterString);
try {
- String engineName = st.nextToken();
- this.engines.put(
- engineName,
- MultiASAPEngineFS_Impl.createMultiEngine(engineName,
- TESTS_ROOT_FOLDER + "/" + engineName,
- this.waitPeriod, null));
+ String peerName = st.nextToken();
+ this.createPeer(peerName);
}
catch(RuntimeException e) {
- this.printUsage(CREATE_ASAP_ENGINE, e.getLocalizedMessage());
+ this.printUsage(CREATE_ASAP_PEER, e.getLocalizedMessage());
} catch (IOException | ASAPException e) {
- this.printUsage(CREATE_ASAP_ENGINE, e.getLocalizedMessage());
+ this.printUsage(CREATE_ASAP_PEER, e.getLocalizedMessage());
}
}
- public void doCreateASAPApp(String parameterString) {
+ public void doCreateASAPApp(String parameterString) throws ASAPException {
StringTokenizer st = new StringTokenizer(parameterString);
try {
- String owner = st.nextToken();
+ String peer = st.nextToken();
String appName = st.nextToken();
- String appFolderName = TESTS_ROOT_FOLDER + "/" + owner + "/" + appName;
-
- ASAPStorage storage = ASAPEngineFS.getASAPStorage(owner, appFolderName, appName);
- if(!storage.isASAPManagementStorageSet()) {
- storage.setASAPManagementStorage(ASAPEngineFS.getASAPStorage(owner,
- TESTS_ROOT_FOLDER + "/" + owner + "/ASAPManagement",
- ASAP_1_0.ASAP_MANAGEMENT_FORMAT));
+ ASAPInternalPeer asapInternalPeer = this.peers.get(peer);
+ if(asapInternalPeer != null) {
+ ASAPInternalStorage storage = asapInternalPeer.createEngineByFormat(appName);
+ /*
+ if(!storage.isASAPManagementStorageSet()) {
+ storage.setASAPManagementStorage(ASAPEngineFS.getASAPStorage(peer,
+ PEERS_ROOT_FOLDER + "/" + peer + "/ASAPManagement",
+ ASAP_1_0.ASAP_MANAGEMENT_FORMAT));
+ }*/
}
-
- this.storages.put(this.getStorageKey(owner, appName), storage);
}
catch(RuntimeException e) {
this.printUsage(CREATE_ASAP_APP, e.getLocalizedMessage());
@@ -442,15 +547,15 @@ public void doCreateASAPApp(String parameterString) {
}
}
- public void doCreateASAPChannel(String parameterString) {
+ public void doCreateASAPChannel(String parameterString) throws ASAPException {
StringTokenizer st = new StringTokenizer(parameterString);
try {
- String owner = st.nextToken();
+ String peername = st.nextToken();
String appName = st.nextToken();
String uri = st.nextToken();
- ASAPStorage storage = this.storages.get(this.getStorageKey(owner, appName));
+ ASAPInternalStorage storage = this.getEngine(peername, appName);
Set recipients = new HashSet<>();
@@ -462,10 +567,10 @@ public void doCreateASAPChannel(String parameterString) {
recipients.add(st.nextToken());
}
- // finally add owner
- recipients.add(owner);
+ // finally add peername
+ recipients.add(peername);
- storage.createChannel(owner, uri, recipients);
+ storage.createChannel(peername, uri, recipients);
}
catch(RuntimeException e) {
this.printUsage(CREATE_ASAP_CHANNEL, e.getLocalizedMessage());
@@ -474,35 +579,38 @@ public void doCreateASAPChannel(String parameterString) {
}
}
- public void doCreateASAPMessage(String parameterString) {
+ public void doCreateASAPMessage(String parameterString) throws ASAPException {
StringTokenizer st = new StringTokenizer(parameterString);
try {
- String owner = st.nextToken();
+ String peername = st.nextToken();
String appName = st.nextToken();
String uri = st.nextToken();
String message = st.nextToken();
// first - get storage
- ASAPStorage asapStorage = this.storages.get(this.getStorageKey(owner, appName));
+ ASAPInternalStorage asapStorage = this.getEngine(peername, appName);
if(asapStorage == null) {
- System.err.println("storage does not exist: " + this.getStorageKey(owner, appName));
+ this.standardError.println("storage does not exist: " + peername + ":" + appName);
return;
}
asapStorage.add(uri, message);
}
catch(RuntimeException e) {
this.printUsage(CREATE_ASAP_MESSAGE, e.getLocalizedMessage());
- } catch (IOException e) {
+ } catch (IOException | ASAPException e) {
this.printUsage(CREATE_ASAP_MESSAGE, e.getLocalizedMessage());
}
}
public void doResetASAPStorages() {
- ASAPEngineFS.removeFolder("tests");
+ FSUtils.removeFolder(PEERS_ROOT_FOLDER);
+ File rootFolder = new File(PEERS_ROOT_FOLDER);
+ rootFolder.mkdirs();
+
}
- public void doSetSendReceivedMessage(String parameterString) {
+ public void doSetSendReceivedMessage(String parameterString) throws ASAPException {
StringTokenizer st = new StringTokenizer(parameterString);
try {
@@ -511,29 +619,30 @@ public void doSetSendReceivedMessage(String parameterString) {
boolean on = this.parseOnOffValue(onOff);
- ASAPStorage storage = this.getStorage(storageName);
- storage.setSendReceivedChunks(on);
+ ASAPEngine engine = this.getEngine(storageName);
+ engine.setBehaviourAllowRouting(on);
}
catch(RuntimeException | IOException | ASAPException e) {
this.printUsage(SET_SEND_RECEIVED_MESSAGES, e.getLocalizedMessage());
}
}
- public void doPrintAllInformation(String parameterString) {
- StringTokenizer st = new StringTokenizer(parameterString);
-
+ public void doPrintAllInformation() throws ASAPException {
try {
- String owner = st.nextToken();
-
- MultiASAPEngineFS multiEngine =
- MultiASAPEngineFS_Impl.createMultiEngine(TESTS_ROOT_FOLDER + "/" + owner, null);
-
- for(CharSequence format : multiEngine.getFormats()) {
- ASAPEngine asapStorage = multiEngine.getEngineByFormat(format);
- System.out.println("storage: " + format);
- for (CharSequence uri : asapStorage.getChannelURIs()) {
- this.printChannelInfo(asapStorage, uri, format);
+ this.standardOut.println(this.peers.keySet().size() + " peers in folder: " + PEERS_ROOT_FOLDER);
+ for(String peername : this.peers.keySet()) {
+ this.standardOut.println("+++++++++++++++++++");
+ this.standardOut.println("Peer: " + peername);
+ ASAPInternalPeer asapInternalPeer = this.peers.get(peername);
+
+ for (CharSequence format : asapInternalPeer.getFormats()) {
+ ASAPEngine asapStorage = asapInternalPeer.getEngineByFormat(format);
+ this.standardOut.println("storage: " + format);
+ for (CharSequence uri : asapStorage.getChannelURIs()) {
+ this.printChannelInfo(asapStorage, uri, format);
+ }
}
+ this.standardOut.println("+++++++++++++++++++\n");
}
}
catch(RuntimeException | IOException | ASAPException e) {
@@ -541,43 +650,76 @@ public void doPrintAllInformation(String parameterString) {
}
}
- public void doPrintStorageInformation(String parameterString) {
+ public void doPrintStorageInformation(String parameterString) throws ASAPException {
StringTokenizer st = new StringTokenizer(parameterString);
try {
- String owner = st.nextToken();
+ String peername = st.nextToken();
String appName = st.nextToken();
// first - get storage
- ASAPStorage asapStorage = this.storages.get(this.getStorageKey(owner, appName));
+ ASAPInternalStorage asapStorage = this.getEngine(peername, appName);
if(asapStorage == null) {
- System.err.println("storage does not exist: " + this.getStorageKey(owner, appName));
+ this.standardError.println("storage does not exist: " + peername + ":" + appName);
return;
}
// iterate URI
+ this.standardOut.println(asapStorage.getChannelURIs().size() +
+ " channels in storage " + appName +
+ " (note: channels without messages are considered non-existent)");
for(CharSequence uri : asapStorage.getChannelURIs()) {
this.doPrintChannelInformation(parameterString + " " + uri);
}
}
- catch(RuntimeException | IOException e) {
+ catch(RuntimeException | IOException | ASAPException e) {
this.printUsage(PRINT_STORAGE_INFORMATION, e.getLocalizedMessage());
}
}
- public void doPrintChannelInformation(String parameterString) {
+ public void doSleep(String parameterString) throws ASAPException {
+ StringTokenizer st = new StringTokenizer(parameterString);
+
+ try {
+ Thread.sleep(Long.parseLong(parameterString));
+ }
+ catch(InterruptedException e) {
+ this.standardOut.println("sleep interrupted");
+ }
+ catch(RuntimeException e) {
+ this.printUsage(PRINT_STORAGE_INFORMATION, e.getLocalizedMessage());
+ }
+ }
+
+ private void doShowLog() {
+ if(this.cmds.size() < 1) return;
+
+ boolean first = true;
+ for(String c : this.cmds) {
+ if (!first) {
+ this.standardOut.println("\\n\" + ");
+ } else {
+ first = false;
+ }
+ this.standardOut.print("\"");
+ this.standardOut.print(c);
+ }
+ this.standardOut.println("\"");
+ }
+
+ public void doPrintChannelInformation(String parameterString) throws ASAPException {
// out.println("example: " + PRINT_CHANNEL_INFORMATION + " Alice chat sn2://abChat");
StringTokenizer st = new StringTokenizer(parameterString);
try {
- String owner = st.nextToken();
+ String peername = st.nextToken();
String appName = st.nextToken();
String uri = st.nextToken();
// first - get storage
- ASAPStorage asapStorage = this.storages.get(this.getStorageKey(owner, appName));
+ ASAPInternalStorage asapStorage = this.getEngine(peername, appName);
if(asapStorage == null) {
- System.err.println("storage does not exist: " + this.getStorageKey(owner, appName));
+ this.standardError.println("storage does not exist: " + peername + ":" + appName);
return;
}
@@ -589,18 +731,19 @@ public void doPrintChannelInformation(String parameterString) {
}
}
- private void printChannelInfo(ASAPStorage asapStorage, CharSequence uri, CharSequence appName)
+ private void printChannelInfo(ASAPInternalStorage asapStorage, CharSequence uri, CharSequence appName)
throws IOException, ASAPException {
+
ASAPChannel channel = asapStorage.getChannel(uri);
Set recipients = channel.getRecipients();
- System.out.println("Owner:App:Channel == " + channel.getOwner() + ":" + appName + ":" + channel.getUri());
- System.out.println("#Messages == " + channel.getMessages().size());
- System.out.println("#Recipients == " + recipients.size());
+ this.standardOut.println("Peer:App:Channel == " + channel.getOwner() + ":" + appName + ":" + channel.getUri());
+ this.standardOut.println("#Messages == " + channel.getMessages().size());
+ this.standardOut.println("#Recipients == " + recipients.size() +
+ " (0 means: open channel - no restrictions - anybody receives from this channel)");
for(CharSequence recipient : recipients) {
- System.out.println(recipient);
+ this.standardOut.println(recipient);
}
-
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -614,11 +757,14 @@ private String getUriFromStorageName(String storageName) throws ASAPException {
return storageName.substring(i);
}
- private ASAPStorage getStorage(String storageName) throws ASAPException {
- ASAPStorage asapStorage = this.storages.get(storageName);
- if(asapStorage == null) throw new ASAPException("no storage with name: " + storageName);
+ private ASAPEngine getEngine(String storageName) throws ASAPException, IOException {
+ // split name into peer and storage
+ String[] split = storageName.split(":");
- return asapStorage;
+ ASAPEngine asapEngine = this.getEngine(split[0], split[1]);
+ if(asapEngine == null) throw new ASAPException("no storage with name: " + storageName);
+
+ return asapEngine;
}
private boolean parseOnOffValue(String onOff) throws ASAPException {
@@ -629,9 +775,8 @@ private boolean parseOnOffValue(String onOff) throws ASAPException {
}
- public String getEngineRootFolderByStorageName(String storageName) throws ASAPException {
-
- ASAPEngineFS asapEngineFS = (ASAPEngineFS) this.getStorage(storageName);
+ public String getEngineRootFolderByStorageName(String storageName) throws ASAPException, IOException {
+ ASAPEngineFS asapEngineFS = (ASAPEngineFS) this.getEngine(storageName);
return asapEngineFS.getRootFolder();
}
}
\ No newline at end of file
diff --git a/src/main/java/net/sharksystem/asap/cmdline/ExampleASAPChunkReceivedListener.java b/src/main/java/net/sharksystem/asap/cmdline/ExampleASAPChunkReceivedListener.java
new file mode 100644
index 0000000..31e97b5
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/cmdline/ExampleASAPChunkReceivedListener.java
@@ -0,0 +1,56 @@
+package net.sharksystem.asap.cmdline;
+
+import net.sharksystem.asap.ASAPHop;
+import net.sharksystem.asap.ASAPMessages;
+import net.sharksystem.asap.engine.ASAPChunkAssimilatedListener;
+import net.sharksystem.utils.Log;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// ASAP API: callbacks ASAPChunkReceived //
+////////////////////////////////////////////////////////////////////////////////////////////////////////////
+public class ExampleASAPChunkReceivedListener implements ASAPChunkAssimilatedListener {
+ private final String rootFolder;
+ private List receivedList = new ArrayList<>();
+
+ public ExampleASAPChunkReceivedListener(String rootFolder) {
+ this.rootFolder = rootFolder;
+ }
+
+ @Override
+ public void chunkStored(String format, String senderE2E, String uri, int era,
+ List asapHop) throws IOException {
+
+ this.receivedList.add(new ASAPChunkReceivedParameters(format, senderE2E, uri, era));
+ }
+
+ @Override
+ public void transientMessagesReceived(ASAPMessages transientMessages, ASAPHop asapHop) throws IOException {
+ Log.writeLog(this, "transient message received - TODO?");
+ }
+
+ public List getReceivedList() { return this.receivedList; }
+
+ public class ASAPChunkReceivedParameters {
+ private final String format;
+ private final String sender;
+ private final String uri;
+ private final int era;
+
+ private ASAPChunkReceivedParameters(String format, String sender, String uri, int era) {
+ Log.writeLog(this, "ASAPChunkReceivedParameters: chunk received: " + format + " | " + sender + " | " + uri);
+ this.format = format;
+ this.sender = sender;
+ this.uri = uri;
+ this.era = era;
+ }
+
+ public String getFormat() { return this.format; }
+ public String getSender() { return this.sender; }
+ public String getUri() { return this.uri; }
+ public int getEra() { return this.era; }
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/cmdline/TCPASAPPeerFS.java b/src/main/java/net/sharksystem/asap/cmdline/TCPASAPPeerFS.java
new file mode 100644
index 0000000..d3cbd47
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/cmdline/TCPASAPPeerFS.java
@@ -0,0 +1,9 @@
+package net.sharksystem.asap.cmdline;
+
+/**
+ * Run an ASAP peer that can communicate with TCP. It can offer an open tcp server socket.
+ * It can also be used as sub unit of a hub, see ASAPHub project.
+ * It works as an ordinary peer otherwise. It is meant to be used as a repeater.
+ */
+public class TCPASAPPeerFS {
+}
diff --git a/src/net/sharksystem/cmdline/TCPChannel.java b/src/main/java/net/sharksystem/asap/cmdline/TCPStream.java
similarity index 83%
rename from src/net/sharksystem/cmdline/TCPChannel.java
rename to src/main/java/net/sharksystem/asap/cmdline/TCPStream.java
index 05876f3..4a02beb 100644
--- a/src/net/sharksystem/cmdline/TCPChannel.java
+++ b/src/main/java/net/sharksystem/asap/cmdline/TCPStream.java
@@ -1,4 +1,6 @@
-package net.sharksystem.cmdline;
+package net.sharksystem.asap.cmdline;
+
+import net.sharksystem.utils.Log;
import java.io.IOException;
import java.io.InputStream;
@@ -10,11 +12,11 @@
*
* @author thsc
*/
-public class TCPChannel extends Thread {
+public class TCPStream extends Thread {
private final int port;
private final boolean asServer;
private final String name;
- private TCPChannelCreatedListener listener = null;
+ private TCPStreamCreatedListener listener = null;
private Socket socket = null;
private boolean fatalError = false;
@@ -25,18 +27,18 @@ public class TCPChannel extends Thread {
private TCPClient tcpClient = null;
private long waitInMillis = WAIT_LOOP_IN_MILLIS;
- public TCPChannel(int port, boolean asServer, String name, TCPChannelCreatedListener listener) {
+ public TCPStream(int port, boolean asServer, String name, TCPStreamCreatedListener listener) {
this.port = port;
this.asServer = asServer;
this.name = name;
this.listener = listener;
}
- public TCPChannel(int port, boolean asServer, String name) {
+ public TCPStream(int port, boolean asServer, String name) {
this(port, asServer, name, null);
}
- public void setListener(TCPChannelCreatedListener listener) {
+ public void setListener(TCPStreamCreatedListener listener) {
this.listener = listener;
}
@@ -58,7 +60,7 @@ public void kill() {
this.tcpServer.kill();
}
} catch (IOException e) {
- System.err.println("TCPChannel: problems while killing: " + e.getLocalizedMessage());
+ Log.writeLogErr(this, "TCPChannel: problems while killing: " + e.getLocalizedMessage());
}
}
@@ -67,8 +69,8 @@ public void run() {
this.createThread = Thread.currentThread();
try {
if(this.asServer) {
- System.out.println(
- "TCPChannel: note: this implementation will only accept *one* connection attempt as server");
+ Log.writeLog(this,
+ "TCPChannel: note: this implementation will only accept *one* connection attempt as server");
this.tcpServer = new TCPServer();
this.socket = tcpServer.getSocket();
} else {
@@ -78,12 +80,12 @@ public void run() {
// we have got a socket
if(this.listener != null) {
- this.listener.channelCreated(this);
+ this.listener.streamCreated(this);
}
} catch (IOException ex) {
//<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>debug
throw new IOException(s);
}
@@ -166,7 +176,7 @@ Socket getSocket() throws IOException {
b.append("opened port ");
b.append(port);
b.append(" on localhost and wait");
- System.out.println(b.toString());
+ Log.writeLog(this, b.toString());
//>>>>>>>>>>>>>>>>>>>debug
Socket socket = this.srvSocket.accept();
@@ -176,7 +186,7 @@ Socket getSocket() throws IOException {
b.append(name);
b.append("): ");
b.append("connected");
- System.out.println(b.toString());
+ Log.writeLog(this, b.toString());
//>>>>>>>>>>>>>>>>>>>debug
return socket;
@@ -204,7 +214,7 @@ Socket getSocket() throws IOException {
b.append("): ");
b.append("try to connect localhost port ");
b.append(port);
- System.out.println(b.toString());
+ Log.writeLog(this, b.toString());
//>>>>>>>>>>>>>>>>>>>debug
Socket socket = new Socket("localhost", port);
return socket;
@@ -217,7 +227,7 @@ Socket getSocket() throws IOException {
b.append("): ");
b.append("failed / wait and re-try");
b.append(port);
- System.out.println(b.toString());
+ Log.writeLog(this, b.toString());
try {
Thread.sleep(waitInMillis);
} catch (InterruptedException ex) {
diff --git a/src/main/java/net/sharksystem/asap/cmdline/TCPStreamCreatedListener.java b/src/main/java/net/sharksystem/asap/cmdline/TCPStreamCreatedListener.java
new file mode 100644
index 0000000..7a5a416
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/cmdline/TCPStreamCreatedListener.java
@@ -0,0 +1,5 @@
+package net.sharksystem.asap.cmdline;
+
+public interface TCPStreamCreatedListener {
+ void streamCreated(TCPStream channel);
+}
diff --git a/src/main/java/net/sharksystem/asap/crypto/ASAPCryptoAlgorithms.java b/src/main/java/net/sharksystem/asap/crypto/ASAPCryptoAlgorithms.java
new file mode 100644
index 0000000..a22736e
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/crypto/ASAPCryptoAlgorithms.java
@@ -0,0 +1,267 @@
+package net.sharksystem.asap.crypto;
+
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPSecurityException;
+import net.sharksystem.asap.utils.ASAPSerialization;
+
+import javax.crypto.*;
+import javax.crypto.spec.SecretKeySpec;
+import java.io.*;
+import java.security.*;
+import java.util.Base64;
+
+public class ASAPCryptoAlgorithms {
+ /**
+ * Produces a byte array that consists of:
+ * RecipientID | asymmetrically encrypted symmetric key | symmetrically encrypted text
+ * @param unencryptedBytes text to be encrypted
+ * @param recipient
+ * @param ASAPKeyStore
+ * @return
+ * @throws ASAPSecurityException
+ */
+ public static void writeEncryptedMessagePackage(byte[] unencryptedBytes, CharSequence recipient,
+ ASAPKeyStore ASAPKeyStore, OutputStream os) throws ASAPSecurityException {
+
+ PublicKey publicKey = ASAPKeyStore.getPublicKey(recipient);
+ // there should be an exception - but better safe than sorry
+ if(publicKey == null) {
+ throw new ASAPSecurityException("recipients' public key cannot be found");
+ }
+
+ try {
+ // send receiver - unencrypted - need this for ad-hoc routing
+ ASAPSerialization.writeCharSequenceParameter(recipient, os);
+
+ // get symmetric key
+ SecretKey encryptionKey = ASAPKeyStore.generateSymmetricKey();
+ byte[] encodedSymmetricKey = encryptionKey.getEncoded();
+
+ // encrypt symmetric key
+ Cipher cipher = Cipher.getInstance(ASAPKeyStore.getAsymmetricEncryptionAlgorithm());
+ cipher.init(Cipher.ENCRYPT_MODE, publicKey);
+ byte[] encryptedSymmetricKeyBytes = cipher.doFinal(encodedSymmetricKey);
+
+ // send encrypted key
+ ASAPSerialization.writeByteArray(encryptedSymmetricKeyBytes, os);
+
+ byte[] encryptedText = encryptSymmetric(unencryptedBytes, encryptionKey, ASAPKeyStore);
+
+ // send encrypted bytes
+ ASAPSerialization.writeByteArray(encryptedText, os);
+
+ } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException
+ | IllegalBlockSizeException | BadPaddingException | IOException e) {
+ throw new ASAPSecurityException("problems when encrypting", e);
+ }
+ }
+
+ public static byte[] produceEncryptedMessagePackage(byte[] unencryptedBytes, CharSequence recipient,
+ ASAPKeyStore ASAPKeyStore) throws ASAPSecurityException {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ writeEncryptedMessagePackage(unencryptedBytes, recipient, ASAPKeyStore, baos);
+ // return whole block of bytes
+ return baos.toByteArray();
+ }
+
+ public static SecretKey createSymmetricKey(byte[] encodedSymmetricKey,
+ ASAPKeyStore ASAPKeyStore) {
+ return new SecretKeySpec(encodedSymmetricKey, ASAPKeyStore.getSymmetricKeyType());
+ }
+
+ /**
+ * Decrypt content from an encrypted message package
+ * @param encryptedMessagePackage package (most likely received from another peer)
+ * @param asapKeyStore peers' key store
+ * @return decrypted message
+ * @throws ASAPSecurityException cannot decrypt - most likely: this peer is not receiver.
+ */
+ public static byte[] decryptPackage(EncryptedMessagePackage encryptedMessagePackage,
+ ASAPKeyStore asapKeyStore) throws ASAPSecurityException {
+
+ byte[] encodedSymmetricKey = decryptAsymmetric(
+ encryptedMessagePackage.getEncryptedSymmetricKey(),
+ asapKeyStore);
+
+ // create symmetric key object
+ SecretKey symmetricKey = createSymmetricKey(encodedSymmetricKey, asapKeyStore);
+
+
+ // decrypt content
+ return decryptSymmetric(encryptedMessagePackage.getEncryptedContent(), symmetricKey, asapKeyStore);
+ }
+
+ public static SecretKey generateSymmetricKey(String keyType, int size) throws ASAPSecurityException {
+ try {
+ KeyGenerator gen = KeyGenerator.getInstance(keyType);
+ gen.init(size);
+ SecretKey secretKey = gen.generateKey();
+ return secretKey;
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ throw new ASAPSecurityException(ASAPCryptoAlgorithms.class.getSimpleName(), e);
+ }
+ }
+
+ public static boolean sameID(CharSequence peerA, CharSequence peerB) {
+ String peerAString = peerA.toString();
+ String peerBString = peerB.toString();
+
+ return peerAString.equalsIgnoreCase(peerBString);
+ }
+
+ public interface EncryptedMessagePackage {
+ CharSequence getReceiver();
+ byte[] getEncryptedSymmetricKey();
+ byte[] getEncryptedContent();
+ }
+
+ public static EncryptedMessagePackage parseEncryptedMessagePackage(byte[] encryptedPackage)
+ throws IOException, ASAPException {
+
+ ByteArrayInputStream bais = new ByteArrayInputStream(encryptedPackage);
+ return ASAPCryptoAlgorithms.parseEncryptedMessagePackage(bais);
+ }
+
+ public static EncryptedMessagePackage parseEncryptedMessagePackage(InputStream is) throws IOException, ASAPException {
+ String recipient = ASAPSerialization.readCharSequenceParameter(is);
+ byte[] encryptedSymmetricKey = ASAPSerialization.readByteArray(is);
+ byte[] encryptedContent = ASAPSerialization.readByteArray(is);
+
+ return new EncryptedMessagePackage() {
+ @Override
+ public CharSequence getReceiver() { return recipient; }
+ @Override
+ public byte[] getEncryptedSymmetricKey() { return encryptedSymmetricKey; }
+ @Override
+ public byte[] getEncryptedContent() { return encryptedContent; }
+ };
+ }
+
+ public static void writeEncryptedMessagePackage(EncryptedMessagePackage encryptedPackage, OutputStream os)
+ throws IOException, ASAPException {
+ ASAPSerialization.writeCharSequenceParameter(encryptedPackage.getReceiver(), os);
+ ASAPSerialization.writeByteArray(encryptedPackage.getEncryptedSymmetricKey(), os);
+ ASAPSerialization.writeByteArray(encryptedPackage.getEncryptedContent(), os);
+ }
+
+ public static byte[] getEncryptedMessagePackageAsBytes(EncryptedMessagePackage encryptedPackage)
+ throws IOException, ASAPException {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ writeEncryptedMessagePackage(encryptedPackage, baos);
+ return baos.toByteArray();
+ }
+
+ /**
+ *
+ * @param unencryptedBytes
+ * @param encryptionKey
+ * @return
+ */
+ public static byte[] encryptSymmetric(byte[] unencryptedBytes, SecretKey encryptionKey,
+ ASAPKeyStore ASAPKeyStore) throws ASAPSecurityException {
+
+ try {
+ // encrypt message with symmetric key
+ Cipher symmetricCipher = Cipher.getInstance(ASAPKeyStore.getSymmetricEncryptionAlgorithm());
+ symmetricCipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
+
+ /*
+ // block by block
+ int i = 0;
+ while(i + MAX_ENCRYPTION_BLOCK_SIZE < asapMessageAsBytes.length) {
+ symmetricCipher.update(asapMessageAsBytes, i, MAX_ENCRYPTION_BLOCK_SIZE);
+ i += MAX_ENCRYPTION_BLOCK_SIZE;
+ }
+
+ int lastStepLen = asapMessageAsBytes.length - i;
+ symmetricCipher.update(asapMessageAsBytes, i, lastStepLen);
+ // did not work - ignored previous updates. anyway, there is a solution, see below
+ byte[] encryptedContent = symmetricCipher.doFinal();
+ */
+
+ // encrypt text with symmetric key
+ return symmetricCipher.doFinal(unencryptedBytes);
+ } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException
+ | IllegalBlockSizeException | BadPaddingException e) {
+ e.printStackTrace();
+ throw new ASAPSecurityException("symmetric encryption failed: "
+ + ASAPKeyStore.getSymmetricEncryptionAlgorithm(), e);
+ }
+ }
+
+ public static byte[] decryptSymmetric(byte[] encryptedContent, SecretKey symmetricKey,
+ ASAPKeyStore ASAPKeyStore) throws ASAPSecurityException {
+
+ try {
+ Cipher symmetricCipher = Cipher.getInstance(ASAPKeyStore.getSymmetricEncryptionAlgorithm());
+ symmetricCipher.init(Cipher.DECRYPT_MODE, symmetricKey);
+ return symmetricCipher.doFinal(encryptedContent);
+ } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException
+ | IllegalBlockSizeException | BadPaddingException e) {
+ e.printStackTrace();
+ throw new ASAPSecurityException("symmetric decryption failed: "
+ + ASAPKeyStore.getSymmetricEncryptionAlgorithm(), e);
+ }
+ }
+
+ public static byte[] decryptAsymmetric(byte[] encryptedBytes, ASAPKeyStore ASAPKeyStore)
+ throws ASAPSecurityException {
+ try {
+ Cipher cipher = Cipher.getInstance(ASAPKeyStore.getAsymmetricEncryptionAlgorithm());
+ cipher.init(Cipher.DECRYPT_MODE, ASAPKeyStore.getPrivateKey());
+ return cipher.doFinal(encryptedBytes);
+ } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException
+ | IllegalBlockSizeException | BadPaddingException e) {
+ e.printStackTrace();
+ throw new ASAPSecurityException("asymmetric decryption failed: "
+ + ASAPKeyStore.getAsymmetricEncryptionAlgorithm(), e);
+ }
+ }
+
+ public static byte[] sign(byte[] bytes2Sign, ASAPKeyStore ASAPKeyStore)
+ throws ASAPSecurityException {
+
+ try {
+ Signature signature = Signature.getInstance(ASAPKeyStore.getAsymmetricSigningAlgorithm());
+ signature.initSign(ASAPKeyStore.getPrivateKey());
+ signature.update(bytes2Sign);
+ return signature.sign();
+ } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ throw new ASAPSecurityException("signing failed: " + ASAPKeyStore.getAsymmetricSigningAlgorithm(), e);
+ }
+ }
+
+ public static boolean verify(byte[] signedData, byte[] signatureBytes, String sender,
+ ASAPKeyStore ASAPKeyStore) throws ASAPSecurityException {
+
+ PublicKey publicKey = ASAPKeyStore.getPublicKey(sender);
+ if(publicKey == null) return false;
+
+ try {
+ Signature signature = Signature.getInstance(ASAPKeyStore.getAsymmetricSigningAlgorithm());
+ signature.initVerify(publicKey); // init with private key
+ signature.update(signedData); // feed with signed data
+ return signature.verify(signatureBytes); // check against signature
+ } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
+ e.printStackTrace();
+ throw new ASAPSecurityException("verifying failed: " + ASAPKeyStore.getAsymmetricSigningAlgorithm(), e);
+ }
+ }
+
+ /**
+ * Produces a Base 64 fingerprint with SHA256.
+ * This fingerprint is not necessarily identical to others.
+ * It an ASAP standard, though.
+ * @param publicKey
+ * @return
+ */
+ public static String getFingerprint(PublicKey publicKey) throws NoSuchAlgorithmException {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ byte[] result = digest.digest(publicKey.getEncoded());
+ return Base64.getEncoder().encodeToString(result);
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/crypto/ASAPCryptoParameterStorage.java b/src/main/java/net/sharksystem/asap/crypto/ASAPCryptoParameterStorage.java
new file mode 100644
index 0000000..3301e7c
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/crypto/ASAPCryptoParameterStorage.java
@@ -0,0 +1,49 @@
+package net.sharksystem.asap.crypto;
+
+import net.sharksystem.asap.ASAPSecurityException;
+
+import javax.crypto.SecretKey;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+
+/**
+ * Defines basic methods we need to implement signing and verification and to get information how to encrypt
+ */
+public interface ASAPCryptoParameterStorage {
+ String DEFAULT_ASYMMETRIC_ENCRYPTION_ALGORITHM = "RSA/ECB/PKCS1Padding";
+ String DEFAULT_SYMMETRIC_KEY_TYPE = "AES";
+ String DEFAULT_SYMMETRIC_ENCRYPTION_ALGORITHM = "AES/ECB/PKCS5Padding";
+ // public static int DEFAULT_AES_KEY_SIZE = 256;
+ int DEFAULT_SYMMETRIC_KEY_SIZE = 128; // TODO we can do better
+ String DEFAULT_ASYMMETRIC_SIGNATURE_ALGORITHM = "SHA256withRSA";
+
+ /**
+ *
+ * @return private key of local device - for signing
+ * @throws ASAPSecurityException
+ */
+ PrivateKey getPrivateKey() throws ASAPSecurityException;
+
+ // debugging
+// PrivateKey getPrivateKey(CharSequence subjectID) throws ASAPSecurityException;
+
+ /**
+ * @return public key of local device - for signing
+ * @throws ASAPSecurityException
+ */
+ PublicKey getPublicKey() throws ASAPSecurityException;
+
+ long getKeysCreationTime() throws ASAPSecurityException;
+
+ String getAsymmetricEncryptionAlgorithm();
+
+ String getAsymmetricSigningAlgorithm();
+
+ SecretKey generateSymmetricKey() throws ASAPSecurityException;
+
+ String getSymmetricEncryptionAlgorithm();
+
+ String getSymmetricKeyType();
+
+ int getSymmetricKeyLen();
+}
diff --git a/src/main/java/net/sharksystem/asap/crypto/ASAPKeyStore.java b/src/main/java/net/sharksystem/asap/crypto/ASAPKeyStore.java
new file mode 100644
index 0000000..4607641
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/crypto/ASAPKeyStore.java
@@ -0,0 +1,36 @@
+package net.sharksystem.asap.crypto;
+
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPSecurityException;
+import net.sharksystem.fs.ExtraData;
+
+import java.io.IOException;
+import java.security.PublicKey;
+
+/**
+ * Basic requirement to encrypt / decrypt and sign/verify messages.
+ */
+public interface ASAPKeyStore extends ASAPCryptoParameterStorage {
+ /**
+ * @param subjectID
+ * @return public key of recipient - to encrypt
+ * @throws ASAPSecurityException if key cannot be found
+ */
+ PublicKey getPublicKey(CharSequence subjectID) throws ASAPSecurityException;
+
+ /**
+ *
+ * @param peerID
+ * @return true if peerID is owners' id.
+ */
+ boolean isOwner(CharSequence peerID);
+
+ CharSequence getOwner();
+
+ /**
+ * A new key pair is created
+ */
+ void generateKeyPair() throws ASAPSecurityException;
+
+ void setMementoTarget(ExtraData extraData);
+}
diff --git a/src/main/java/net/sharksystem/asap/crypto/ASAPPoint2PointCryptoSettings.java b/src/main/java/net/sharksystem/asap/crypto/ASAPPoint2PointCryptoSettings.java
new file mode 100644
index 0000000..28adc3e
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/crypto/ASAPPoint2PointCryptoSettings.java
@@ -0,0 +1,6 @@
+package net.sharksystem.asap.crypto;
+
+public interface ASAPPoint2PointCryptoSettings {
+ boolean mustEncrypt();
+ boolean mustSign();
+}
diff --git a/src/main/java/net/sharksystem/asap/crypto/ASAPPoint2PointCryptoSettingsImpl.java b/src/main/java/net/sharksystem/asap/crypto/ASAPPoint2PointCryptoSettingsImpl.java
new file mode 100644
index 0000000..65e5c76
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/crypto/ASAPPoint2PointCryptoSettingsImpl.java
@@ -0,0 +1,20 @@
+package net.sharksystem.asap.crypto;
+
+public class ASAPPoint2PointCryptoSettingsImpl implements ASAPPoint2PointCryptoSettings {
+ private final boolean encrypt;
+ private final boolean sign;
+
+ public ASAPPoint2PointCryptoSettingsImpl(boolean encrypt, boolean sign) {
+ this.encrypt = encrypt;
+ this.sign = sign;
+ }
+ @Override
+ public boolean mustEncrypt() {
+ return this.encrypt;
+ }
+
+ @Override
+ public boolean mustSign() {
+ return this.sign;
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/crypto/InMemoASAPKeyStore.java b/src/main/java/net/sharksystem/asap/crypto/InMemoASAPKeyStore.java
new file mode 100644
index 0000000..03139a7
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/crypto/InMemoASAPKeyStore.java
@@ -0,0 +1,353 @@
+package net.sharksystem.asap.crypto;
+
+import net.sharksystem.SharkException;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPSecurityException;
+import net.sharksystem.asap.utils.ASAPSerialization;
+import net.sharksystem.fs.ExtraData;
+import net.sharksystem.utils.Log;
+
+import javax.crypto.SecretKey;
+import java.io.*;
+import java.security.*;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.HashMap;
+
+public class InMemoASAPKeyStore implements ASAPKeyStore {
+ private static final CharSequence ASAP_KEYSTORE_MEMENTO_KEY = "asapKeyStoreMemento";
+ private PrivateKey privateKey;
+ private PublicKey publicKey;
+ private KeyPair keyPair;
+ private CharSequence ownerID;
+ private long keyPairCreationTime = 0;
+
+ // for debugging only - we don't have private key in real apps
+ private HashMap peerKeyPairs = new HashMap<>();
+
+ private HashMap peerPublicKeys = new HashMap();
+
+ /**
+ * Setup key store, A key pair will be generated
+ * @param ownerID
+ * @throws ASAPSecurityException
+ */
+ public InMemoASAPKeyStore(CharSequence ownerID) throws ASAPSecurityException {
+ // generate owners key pair;
+ this.ownerID = ownerID;
+ //this.generateKeyPair();
+ }
+
+ /**
+ * Setup key store with a key pair
+ * @param ownerID
+ * @param ownerKeyPair
+ * @deprecated
+ */
+ public InMemoASAPKeyStore(CharSequence ownerID, KeyPair ownerKeyPair, long keyPairCreationTime) {
+ this.ownerID = ownerID;
+ this.keyPair = ownerKeyPair;
+ if(ownerKeyPair != null) {
+ this.privateKey = ownerKeyPair.getPrivate();
+ this.publicKey = ownerKeyPair.getPublic();
+ }
+
+ this.keyPairCreationTime = keyPairCreationTime;
+ }
+
+ protected void setKeyPair(KeyPair keyPair) {
+ this.keyPair = keyPair;
+ }
+
+ public KeyPair getKeyPair() {
+ if(this.keyPair == null) {
+ Log.writeLog(this, "key pair not yet generated - do it now");
+ try {
+ this.generateKeyPair();
+ } catch (ASAPSecurityException e) {
+ Log.writeLogErr(this, "cannot generate key pair - fatal");
+ e.printStackTrace();
+ return null;
+ }
+ }
+ return this.keyPair;
+ }
+
+ public SecretKey generateSymmetricKey() throws ASAPSecurityException {
+ return ASAPCryptoAlgorithms.generateSymmetricKey(
+ DEFAULT_SYMMETRIC_KEY_TYPE, DEFAULT_SYMMETRIC_KEY_SIZE);
+ }
+
+ public long getKeysCreationTime() throws ASAPSecurityException {
+ return this.keyPairCreationTime;
+ }
+
+ public int getSymmetricKeyLen() {
+ return ASAPKeyStore.DEFAULT_SYMMETRIC_KEY_SIZE;
+ }
+
+ public void generateKeyPair() throws ASAPSecurityException {
+ this.setKeyPair(this.generateNewKeyPair());
+ this.privateKey = this.keyPair.getPrivate();
+ this.publicKey = this.keyPair.getPublic();
+ this.keyPairCreationTime = System.currentTimeMillis();
+ this.save();
+ }
+
+ private KeyPair generateNewKeyPair() throws ASAPSecurityException {
+ Log.writeLog(this, "create key pair");
+ KeyPairGenerator keyGen = null;
+ try {
+ keyGen = KeyPairGenerator.getInstance("RSA");
+ } catch (NoSuchAlgorithmException e) {
+ throw new ASAPSecurityException(e.getLocalizedMessage());
+ }
+
+ SecureRandom secRandom = new SecureRandom();
+ try {
+ keyGen.initialize(2048, secRandom);
+ return keyGen.generateKeyPair();
+ }
+ catch(RuntimeException re) {
+ throw new ASAPSecurityException(re.getLocalizedMessage());
+ }
+ }
+
+ public KeyPair createTestPeer(String id) throws ASAPSecurityException {
+ KeyPair keyPair = this.generateNewKeyPair();
+ this.peerKeyPairs.put(id, keyPair);
+ return keyPair;
+ }
+
+ private void checkKeyPairExistence() throws ASAPSecurityException {
+ if(this.keyPair == null) {
+ Log.writeLog(this, "create new keypair since requested but missing");
+ this.generateKeyPair();
+ this.privateKey = this.keyPair.getPrivate();
+ this.publicKey = this.keyPair.getPublic();
+ }
+ }
+
+ @Override
+ public PrivateKey getPrivateKey() throws ASAPSecurityException {
+ if(this.privateKey == null) {
+ this.checkKeyPairExistence();
+ }
+ return this.privateKey;
+ }
+
+ @Override
+ public PublicKey getPublicKey() throws ASAPSecurityException {
+ if(this.publicKey == null) {
+ this.checkKeyPairExistence();
+ }
+ return this.publicKey;
+ }
+
+ @Override
+ public PublicKey getPublicKey(CharSequence subjectID) throws ASAPSecurityException {
+ KeyPair keyPair = this.peerKeyPairs.get(subjectID);
+ if(keyPair == null) {
+ // try there - which is more likely
+ PublicKey publicKey = this.peerPublicKeys.get(subjectID);
+ if(publicKey != null) {
+ // got it
+ return publicKey;
+ }
+ // else
+ throw new ASAPSecurityException("no key pair for " + subjectID);
+ }
+
+ return keyPair.getPublic();
+ }
+
+ void putPublicKey(CharSequence peer, PublicKey key) {
+ this.peerPublicKeys.put(peer, key);
+ }
+
+ /**
+ * In reality there cannot be such a method - but we are in a test.
+ * @param subjectID
+ * @return
+ * @throws ASAPSecurityException
+ */
+ public PrivateKey getPrivateKey(CharSequence subjectID) throws ASAPSecurityException {
+ KeyPair keyPair = this.peerKeyPairs.get(subjectID);
+ if(keyPair == null) throw new ASAPSecurityException("no key pair for " + subjectID);
+
+ return keyPair.getPrivate();
+ }
+
+ @Override
+ public String getAsymmetricEncryptionAlgorithm() {
+ return DEFAULT_ASYMMETRIC_ENCRYPTION_ALGORITHM;
+ }
+
+ @Override
+ public String getSymmetricEncryptionAlgorithm() {
+ return DEFAULT_SYMMETRIC_ENCRYPTION_ALGORITHM;
+ }
+
+ @Override
+ public String getSymmetricKeyType() {
+ return DEFAULT_SYMMETRIC_KEY_TYPE;
+ }
+
+ @Override
+ public boolean isOwner(CharSequence peerID) {
+ return ASAPCryptoAlgorithms.sameID(this.getOwner(), peerID);
+ }
+
+ @Override
+ public CharSequence getOwner() {
+ return this.ownerID;
+ }
+
+ @Override
+ public String getAsymmetricSigningAlgorithm() {
+ return DEFAULT_ASYMMETRIC_SIGNATURE_ALGORITHM;
+ }
+
+ public void addKeyPair(String peerID, KeyPair keyPair) {
+ this.peerKeyPairs.put(peerID, keyPair);
+ }
+
+ /**
+ * Write storage owners' public key to stream
+ * @param os
+ */
+ public void writePublicKey(OutputStream os) throws ASAPSecurityException, IOException {
+ PublicKey publicKey = this.getPublicKey();
+
+ String format = publicKey.getFormat();
+ String algorithm = publicKey.getAlgorithm();
+ byte[] byteEncodedPublicKey = publicKey.getEncoded();
+ int length = byteEncodedPublicKey.length;
+
+ // makes it much easier to serialize simple data
+ DataOutputStream dos = new DataOutputStream(os);
+
+ // write to stream
+ dos.writeUTF(format);
+ dos.writeUTF(algorithm);
+ dos.writeInt(byteEncodedPublicKey.length);
+
+ // write encoded key directly on stream
+ os.write(byteEncodedPublicKey);
+ }
+
+ /**
+ * Read public key from another peer from an extern source (input stream)
+ * @param peer
+ * @param is
+ */
+ public void readPublicKey(CharSequence peer, InputStream is) throws ASAPSecurityException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {
+ DataInputStream dis = new DataInputStream(is);
+
+ // read in same order as written
+ String format = dis.readUTF();
+ String algorithm = dis.readUTF();
+ int len = dis.readInt();
+
+ // allocate memory
+ byte[] byteEncodedPublicKey = new byte[len];
+
+ // read encoded key directly from stream
+ is.read(byteEncodedPublicKey);
+
+ // create key object
+
+ // should be revised - why?
+ X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(byteEncodedPublicKey);
+
+ KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
+ PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
+
+ // store it
+ this.putPublicKey(peer, publicKey);
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // persist //
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ private ExtraData mementoExtraData;
+
+ public void setMementoTarget(ExtraData extraData) {
+ this.mementoExtraData = extraData;
+ try {
+ byte[] memento = this.mementoExtraData.getExtra(ASAP_KEYSTORE_MEMENTO_KEY);
+ this.restoreMemento(memento);
+ } catch (IOException | SharkException e) {
+ // no memento - hm, maybe was set when this keystore was already running - better save
+ this.save();
+ }
+ }
+
+ private void save() {
+ if(this.mementoExtraData != null) {
+ try {
+ this.mementoExtraData.putExtra(ASAP_KEYSTORE_MEMENTO_KEY, this.getMemento());
+ } catch (IOException | SharkException e) {
+ Log.writeLogErr(this, "cannot write memento: " + e.getLocalizedMessage());
+ }
+ } else {
+ Log.writeLog(this, "cannot write data - no persistent storage");
+ }
+ }
+
+ public byte[] getMemento() throws ASAPException, IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ // encoded private key
+ ASAPSerialization.writeByteArray(this.getPrivateKey().getEncoded(), baos);
+ // private key algorithm
+ ASAPSerialization.writeCharSequenceParameter(this.getPrivateKey().getAlgorithm(), baos);
+ // private key format
+ ASAPSerialization.writeCharSequenceParameter(this.getPrivateKey().getFormat(), baos);
+
+ // public key encoded
+ ASAPSerialization.writeByteArray(this.getPublicKey().getEncoded(), baos);
+ // public key algorithm
+ ASAPSerialization.writeCharSequenceParameter(this.getPublicKey().getAlgorithm(), baos);
+ // public key format
+ ASAPSerialization.writeCharSequenceParameter(this.getPublicKey().getFormat(), baos);
+
+ // creation time
+ ASAPSerialization.writeLongParameter(this.keyPairCreationTime, baos);
+
+ // ownerID
+ ASAPSerialization.writeCharSequenceParameter(this.ownerID, baos);
+
+ return baos.toByteArray();
+ }
+
+ public void restoreMemento(byte[] mementoData) throws IOException, ASAPException {
+ ByteArrayInputStream bais = new ByteArrayInputStream(mementoData);
+
+ byte[] privateKeyBytes = ASAPSerialization.readByteArray(bais);
+ String privateKeyAlgorithm = ASAPSerialization.readCharSequenceParameter(bais);
+ String privateKeyFormat = ASAPSerialization.readCharSequenceParameter(bais);
+
+ byte[] publicKeyBytes = ASAPSerialization.readByteArray(bais);
+ String publicKeyAlgorithm = ASAPSerialization.readCharSequenceParameter(bais);
+ String publicKeyFormat = ASAPSerialization.readCharSequenceParameter(bais);
+
+ // reproduce private key
+ // as to be seen, pretty limited alg/format support yet :/
+ try {
+ KeyFactory kf = KeyFactory.getInstance("RSA");
+ this.privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
+ this.publicKey = kf.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
+ } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
+ throw new ASAPException("cannot restore keystore form memento: " + e.getLocalizedMessage());
+ }
+
+ // reset those simple data after that critical stuff.
+ this.keyPairCreationTime = ASAPSerialization.readLongParameter(bais);
+ this.ownerID = ASAPSerialization.readCharSequenceParameter(bais);
+
+ Log.writeLog(this, "restored keys");
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/crypto/SharkCryptoException.java b/src/main/java/net/sharksystem/asap/crypto/SharkCryptoException.java
new file mode 100644
index 0000000..c8b3c6b
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/crypto/SharkCryptoException.java
@@ -0,0 +1,13 @@
+package net.sharksystem.asap.crypto;
+
+import net.sharksystem.asap.ASAPException;
+
+public class SharkCryptoException extends ASAPException {
+ public SharkCryptoException() { super(); }
+
+ public SharkCryptoException(String message) { super(message); }
+
+ public SharkCryptoException(String message, Throwable cause) { super(message, cause); }
+
+ public SharkCryptoException(Throwable cause) { super(cause); }
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPAbstractOnlineMessageSender.java b/src/main/java/net/sharksystem/asap/engine/ASAPAbstractOnlineMessageSender.java
new file mode 100644
index 0000000..bf537f9
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPAbstractOnlineMessageSender.java
@@ -0,0 +1,31 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.ASAPException;
+
+import java.io.IOException;
+import java.util.*;
+
+public abstract class ASAPAbstractOnlineMessageSender implements ASAPOnlineMessageSender {
+ private ASAPInternalStorage source = null;
+
+ public void attachToSource(ASAPInternalStorage source) {
+ source.attachASAPMessageAddListener(this);
+ }
+
+ public void detachFromStorage() {
+ if(this.source != null) {
+ this.source.detachASAPMessageAddListener();
+ }
+ }
+
+ public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, CharSequence recipient,
+ byte[] messageAsBytes, int era) throws IOException, ASAPException {
+ if(recipient == null) {
+ this.sendASAPAssimilateMessage(format, uri, messageAsBytes, era);
+ } else {
+ Set recipients = new HashSet<>();
+ recipients.add(recipient);
+ this.sendASAPAssimilateMessage(format, uri, recipients, messageAsBytes, era);
+ }
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPChannelImpl.java b/src/main/java/net/sharksystem/asap/engine/ASAPChannelImpl.java
new file mode 100644
index 0000000..d3955a5
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPChannelImpl.java
@@ -0,0 +1,97 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.*;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Set;
+
+public class ASAPChannelImpl implements ASAPChannel {
+ private static final String CHANNEL_OWNER = "ASAPChannelOwner";
+ private final ASAPEngine asapEngine;
+ private final CharSequence uri;
+
+ public ASAPChannelImpl(ASAPEngine asapEngine, CharSequence uri) {
+ this.asapEngine = asapEngine;
+ this.uri = uri;
+ }
+
+ @Override
+ public CharSequence getOwner() throws IOException {
+ return this.asapEngine.getExtra(this.getUri(), CHANNEL_OWNER);
+ }
+
+ @Override
+ public CharSequence getUri() throws IOException {
+ return this.uri;
+ }
+
+ @Override
+ public Set getRecipients() throws IOException {
+ return this.asapEngine.getRecipients(this.getUri());
+ }
+
+ @Override
+ public HashMap getExtraData() throws IOException {
+ return this.asapEngine.getStorage().getChunk(uri, this.asapEngine.getEra()).getExtraData();
+ }
+
+ @Override
+ public void putExtraData(String key, String value) throws IOException {
+ this.asapEngine.getStorage().getChunk(uri, this.asapEngine.getEra()).putExtra(key, value);
+ }
+
+ @Override
+ public void removeExtraData(String key) throws IOException {
+ this.asapEngine.getStorage().getChunk(uri, this.asapEngine.getEra()).removeExtra(key);
+ }
+
+ @Override
+ public ASAPMessages getMessages() throws IOException {
+ return this.asapEngine.getChunkStorage().getASAPMessages(this.getUri(), this.asapEngine.getEra());
+ }
+
+ @Override
+ public ASAPMessages getMessages(boolean peerOnly) throws IOException, ASAPException {
+ if(peerOnly) return this.getMessages();
+ // else
+ return this.getMessages(null);
+ }
+
+ @Override
+ public ASAPMessages getMessages(ASAPMessageCompare compare) throws IOException, ASAPException {
+ List messagesSource = new ArrayList<>();
+
+ // add message from local peer first
+ messagesSource.add(this.getMessages());
+
+ // other sender?
+ List sender = this.asapEngine.getSender();
+ for(CharSequence senderID : sender) {
+ try {
+ ASAPStorage existingIncomingStorage = this.asapEngine.getExistingIncomingStorage(senderID);
+ int currentEra = existingIncomingStorage.getEra();
+ // want all messages
+ int beforeCurrentEra = ASAP.previousEra(currentEra);
+ // currentEra -> direct predecessor
+ messagesSource.add(existingIncomingStorage.getChunkStorage().getASAPMessages(
+ this.getUri(), currentEra, beforeCurrentEra));
+ } catch (ASAPException e) {
+ // no such storage - ok ignore and go ahead
+ }
+ }
+
+ return new ASAPMessagesMerger(messagesSource, compare);
+ }
+
+ @Override
+ public void addMessage(byte[] message) throws IOException {
+ this.asapEngine.add(this.uri, message);
+ }
+
+ public void setOwner(CharSequence owner) throws IOException {
+ this.asapEngine.putExtra(this.getUri(), CHANNEL_OWNER, owner.toString());
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPChunkAssimilatedListener.java b/src/main/java/net/sharksystem/asap/engine/ASAPChunkAssimilatedListener.java
new file mode 100644
index 0000000..48bc63b
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPChunkAssimilatedListener.java
@@ -0,0 +1,35 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.ASAPHop;
+import net.sharksystem.asap.ASAPMessages;
+
+import java.io.IOException;
+import java.util.List;
+
+/**
+ *
+ * @author thsc
+ */
+public interface ASAPChunkAssimilatedListener {
+ /**
+ * Announce incoming ASAP messages. Note the important difference of both senders. ASAP is a routing protocol.
+ * An ASAP message has got an original sender (the end-to-end (E2E) sender). Other peers can route this message.
+ * The final (senderPoint2Point) is not necessarily the E2E sender but the peer on the other side of the channel.
+ *
+ * E2E sender and direct sender are always the same when disengaging routing.
+ * It is recommended to allow routing, though.
+ *
+ * @param format application format
+ * @param senderE2E original sender peer - the E2E sender - not necessarily the sender on the other side of
+ * the channel.
+ * @param uri message uri
+ * @param era era of the original sender (the end-to-end sender). not
+ * @param asapHop describes the point-to-point message exchhange in more details
+ * @see ASAPHop
+ *
+ */
+ void chunkStored(String format, String senderE2E, String uri, int era, // E2E part
+ List asapHop) throws IOException;
+
+ void transientMessagesReceived(ASAPMessages transientMessages, ASAPHop asapHop) throws IOException;
+}
diff --git a/src/net/sharksystem/asap/ASAPChunkStorageFS.java b/src/main/java/net/sharksystem/asap/engine/ASAPChunkStorageFS.java
similarity index 51%
rename from src/net/sharksystem/asap/ASAPChunkStorageFS.java
rename to src/main/java/net/sharksystem/asap/engine/ASAPChunkStorageFS.java
index 1f028c5..648fc84 100644
--- a/src/net/sharksystem/asap/ASAPChunkStorageFS.java
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPChunkStorageFS.java
@@ -1,7 +1,12 @@
-package net.sharksystem.asap;
+package net.sharksystem.asap.engine;
-import net.sharksystem.Utils;
-import net.sharksystem.asap.apps.ASAPMessages;
+import net.sharksystem.utils.Utils;
+import net.sharksystem.asap.ASAP;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPChunkStorage;
+import net.sharksystem.asap.ASAPMessages;
+import net.sharksystem.utils.Log;
+import net.sharksystem.fs.FSUtils;
import java.io.File;
import java.io.FilenameFilter;
@@ -9,36 +14,47 @@
import java.util.ArrayList;
import java.util.List;
-import static net.sharksystem.asap.ASAPChunkFS.META_DATA_EXTENSION;
+import static net.sharksystem.asap.engine.ASAPInternalChunkFS.META_DATA_EXTENSION;
/**
*
* @author thsc
*/
class ASAPChunkStorageFS implements ASAPChunkStorage {
-
private final String rootDirectory;
private final String format;
+ private int era = -1;
ASAPChunkStorageFS(String rootDirectory, String format) {
this.rootDirectory = rootDirectory;
this.format = format;
}
+ ASAPChunkStorageFS(String rootDirectory, String format, int era) {
+ this.rootDirectory = rootDirectory;
+ this.format = format;
+ this.era = era;
+ }
+
public String getFormat() {
- return format;
+ return this.format;
+ }
+
+ public String getRootDirectory() {
+ return this.rootDirectory;
}
@Override
- public ASAPChunk getChunk(CharSequence uriTarget, int era) throws IOException {
- return new ASAPChunkFS(this, uriTarget.toString(), era);
+ public ASAPInternalChunk getChunk(CharSequence uriTarget, int era) throws IOException {
+ return new ASAPInternalChunkFS(this, uriTarget.toString(), era);
}
@Override
public boolean existsChunk(CharSequence uri, int era) throws IOException {
String fullContentFileName = this.getChunkContentFilename(era, uri);
- return(new File(fullContentFileName).exists());
+ boolean exists = (new File(fullContentFileName).exists());
+ return exists;
}
String getChunkContentFilename(int era, CharSequence uri) {
@@ -59,12 +75,16 @@ String getChunkFileTrunkname(int era, String uri) {
String setupChunkFolder(int era, String targetUrl) {
String eraFolderString = this.getPath(era);
File eraFolder = new File(eraFolderString);
+ //Log.writeLog(this, "produced chunk folder name: " + eraFolderString);
if(!eraFolder.exists()) {
+ //Log.writeLog(this, "folder does not exist - create: " + eraFolderString);
eraFolder.mkdirs();
}
-
- String fileName = eraFolderString + "/" + Utils.url2FileName(targetUrl);
- return fileName;
+
+ //Log.writeLog(this, "chunk folder exists: " + eraFolder);
+ String fileNameWithoutExtension = eraFolderString + "/" + Utils.url2FileName(targetUrl);
+ //Log.writeLog(this, "use this file name to store chunk (meta)data: " + fileNameWithoutExtension);
+ return fileNameWithoutExtension;
}
/**
@@ -82,8 +102,8 @@ private String getPath(int era) {
}
@Override
- public List getChunks(int era) throws IOException {
- List chunkList = new ArrayList<>();
+ public List getChunks(int era) throws IOException {
+ List chunkList = new ArrayList<>();
File dir = new File(this.getPath(era));
@@ -104,7 +124,7 @@ public boolean accept(File dir, String fileName) {
if(index != -1) {
String chunkName = name.substring(0, index);
String fName = this.getFileNameByUri(era, chunkName);
- chunkList.add(new ASAPChunkFS(this, fName));
+ chunkList.add(new ASAPInternalChunkFS(this, fName));
}
}
}
@@ -117,22 +137,47 @@ public void dropChunks(int era) throws IOException {
// here comes a Java 6 compatible version - fits to android SDK 23
String eraPathName = this.rootDirectory + "/" + Integer.toString(era);
- ASAPEngineFS.removeFolder(eraPathName);
+ FSUtils.removeFolder(eraPathName);
}
@Override
- public ASAPMessages getASAPChunkCache(CharSequence uri, int toEra) throws IOException {
- // go back 1000 eras
- int fromEra = toEra;
- for(int i = 0; i < 1000; i++) {
- fromEra = ASAPEngine.previousEra(fromEra);
- }
+ public ASAPMessages getASAPMessages(CharSequence uri, int toEra) throws IOException {
+ // INIT ++++++++++++++++++++++ toEra +++++++++++++++++++++ MAX
- return new ASAPInMemoMessages(this,
+ int fromEra = ASAP.nextEra(toEra); // the whole cycle
+ return this.getASAPMessages(uri, fromEra, toEra);
+ }
+
+ @Override
+ public ASAPMessages getASAPMessages(CharSequence uri, int fromEra, int toEra) throws IOException {
+ Log.writeLog(this, "create ASAPInMemoMessages");
+
+ return new ASAPInMemoMessages(
+ this,
this.getFormat(),
uri,
fromEra, // set starting era
toEra // anything before
);
}
+
+ @Override
+ public ASAPMessages getASAPMessages(String uri) throws ASAPException, IOException {
+ if(this.era == -1) {
+ throw new ASAPException("internal error: era not set - use other constructor or method");
+ }
+ return this.getASAPMessages(uri, this.era);
+ }
+
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(this.getClass().getSimpleName());
+ sb.append(": ");
+ sb.append(this.rootDirectory);
+ sb.append(" | ");
+ sb.append(this.format);
+ sb.append(" | ");
+ sb.append(this.era);
+ return sb.toString();
+ }
}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPCommunicationSetting.java b/src/main/java/net/sharksystem/asap/engine/ASAPCommunicationSetting.java
new file mode 100644
index 0000000..0e2f594
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPCommunicationSetting.java
@@ -0,0 +1,18 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.protocol.ASAP_AssimilationPDU_1_0;
+
+interface ASAPCommunicationSetting {
+ boolean allowedToCreateChannel(ASAP_AssimilationPDU_1_0 asapAssimilationPDU);
+
+ /**
+ * @param on if true - message must be encrypted
+ */
+ void setSendEncryptedMessages(boolean on);
+
+ /**
+ * @param on if true - message must be signed
+ */
+ void setSendSignedMessages(boolean on);
+
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPEngine.java b/src/main/java/net/sharksystem/asap/engine/ASAPEngine.java
new file mode 100644
index 0000000..d35103c
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPEngine.java
@@ -0,0 +1,975 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.ASAPHopImpl;
+import net.sharksystem.asap.ASAPEncounterConnectionType;
+import net.sharksystem.asap.*;
+import net.sharksystem.asap.ASAPChunkStorage;
+import net.sharksystem.asap.ASAPMessages;
+import net.sharksystem.asap.listenermanager.management.ASAPManagementStorage;
+import net.sharksystem.asap.listenermanager.management.ASAPManagementStorageImpl;
+import net.sharksystem.asap.protocol.*;
+import net.sharksystem.asap.utils.PeerIDHelper;
+import net.sharksystem.utils.Log;
+import net.sharksystem.asap.crypto.ASAPPoint2PointCryptoSettings;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.*;
+
+/**
+ * That ASAPEngine manages exchange of stored messages with peers.
+ * See ASPChunkStorage for details.
+ *
+ * @see ASAPInternalStorage
+ * @author thsc
+ */
+public abstract class ASAPEngine extends ASAPStorageImpl implements ASAPInternalStorage, ASAPProtocolEngine, ASAPManagementStorage {
+ private DefaultSecurityAdministrator securityAdministrator;
+
+ public void setSecurityAdministrator(DefaultSecurityAdministrator securityAdministrator) {
+ this.securityAdministrator = securityAdministrator;
+ }
+
+ public static final String ANONYMOUS_OWNER = "anon";
+ static String DEFAULT_OWNER = ANONYMOUS_OWNER;
+ static int DEFAULT_INIT_ERA = 0;
+
+ protected String owner = ANONYMOUS_OWNER;
+
+ protected int era = ASAP.INITIAL_ERA;
+ protected int oldestEra = ASAP.INITIAL_ERA;
+ protected HashMap lastSeen = new HashMap<>();
+ protected ASAPMemento memento = null;
+ public long lastMementoWritten;
+
+ protected boolean dropDeliveredChunks = false;
+
+ private ASAPOnlineMessageSender asapOnlineMessageSender;
+ protected boolean contentChanged = false;
+ protected boolean routingAllowed = true;
+
+ protected ASAPEngine(ASAPChunkStorage chunkStorage, CharSequence chunkContentFormat)
+ throws ASAPException, IOException {
+ //super(chunkStorage, chunkContentFormat);
+
+ this.chunkStorage = chunkStorage;
+ if(chunkContentFormat != null) {
+ this.format = chunkContentFormat.toString();
+ } else {
+ throw new ASAPException("format expected. like application/x-sn2-makan");
+ }
+ }
+
+ private void saveStatus() throws IOException {
+ if (this.memento != null) {
+ this.memento.save(this);
+ }
+ }
+
+ CryptoControl getCryptoControl() {
+ return this.securityAdministrator;
+ }
+
+ public ASAPEnginePermissionSettings getASAPEnginePermissionSettings() {
+ return this.securityAdministrator;
+ }
+
+ public ASAPCommunicationSetting getASAPCommunicationControl() {
+ return this.securityAdministrator;
+ }
+
+ public ASAPPoint2PointCryptoSettings getASAPCommunicationCryptoSettings() {
+ return this.securityAdministrator;
+ }
+
+ public void attachASAPMessageAddListener(ASAPOnlineMessageSender asapOnlineMessageSender) {
+ this.asapOnlineMessageSender = asapOnlineMessageSender;
+ }
+
+ public void detachASAPMessageAddListener() {
+ this.asapOnlineMessageSender = null;
+ }
+
+ /**
+ * We interpret an existing chunk with *no* recipients as
+ * public chunk
+ * @param chunk
+ * @return
+ */
+ private boolean isPublic(ASAPInternalChunk chunk) {
+ return chunk.getRecipients().isEmpty();
+ }
+
+ abstract void syncMemento() throws IOException;
+
+ @Override
+ public void newEra() {
+ this.newEra(false, -1);
+ }
+
+ /**
+ * Set a new ear in this storage - if forced: set newEra as specified without questioning
+ * @param force
+ * @param nextEra
+ */
+ private void newEra(boolean force, int nextEra) {
+ try {
+ this.syncMemento();
+ } catch (IOException e) {
+ Log.writeLogErr(this, this.toString(),"cannot read memento: " + e.getLocalizedMessage());
+ }
+
+ if(force || this.contentChanged) {
+ // set as fast as possible to make race conditions less likely
+ this.contentChanged = false;
+
+ if(force) {
+ Log.writeLog(this, this.toString(), "forced setting era to " + nextEra);
+ } else {
+ // calculate new era
+ nextEra = nextEra < 0 ? this.getNextEra(this.era) : nextEra;
+ Log.writeLog(this, this.toString(), "era not forced - incremented era to " + nextEra);
+ }
+ try {
+ int previousEra = this.era;
+
+ // we are done here - we are in a new era.
+ this.era = nextEra;
+
+ // persistent values
+ if(this.memento != null) this.memento.save(this);
+
+ /* now:
+ previousEra .. era that was used a few milliseconds before. Keep it.
+ this.era .. era we are going to work with
+
+ Now, there could be a very old version with same number as this.era - remove it before you set up
+ fresh era
+ */
+
+ if(this.era == previousEra) {
+ Log.writeLog(this, this.toString(), "this.era == previousEra - nothing to do");
+ } else {
+ // drop very very old chunks - if available - if not - don't care
+ this.getChunkStorage().dropChunks(this.era);
+
+ Log.writeLog(this, this.toString(),
+ "setup new era by cloning previous chunk meta data: "
+ + this.era + " <- " + previousEra);
+ // setup new era - copy all chunks
+ for(ASAPInternalChunk chunk : this.getChunkStorage().getChunks(previousEra)) {
+ Log.writeLog(this, this.toString(),"going to clone: " + chunk);
+ ASAPInternalChunk copyChunk = this.getChunkStorage().getChunk(chunk.getUri(), this.era);
+ copyChunk.clone(chunk);
+ Log.writeLog(this, this.toString(),"done cloning: " + copyChunk);
+ }
+ }
+
+ Log.writeLog(this, this.toString(), "era incremented");
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ Log.writeLogErr(this, this.toString(),
+ "IOException while incrementing era: " + ex.getLocalizedMessage());
+ }
+ } else {
+ Log.writeLog(this, this.toString(), "content not changed - era not changed");
+ }
+ }
+
+ //////////////////////////////////////////////////////////////////////
+ // Writer //
+ //////////////////////////////////////////////////////////////////////
+
+ @Override
+ public void createChannel(CharSequence uri, Collection recipients) throws IOException, ASAPException {
+ this.createChannel(this.getOwner(), uri, recipients);
+ }
+
+ @Override
+ public void createChannel(CharSequence owner, CharSequence uri, Collection recipients)
+ throws IOException, ASAPException {
+
+ this.setRecipients(uri, recipients);
+ this.getASAPChannelImpl(uri).setOwner(owner);
+
+ // inform recipients about that event
+ if(this.isASAPManagementStorageSet()) {
+ this.getASAPManagementStorage().notifyChannelCreated(this.format, owner, uri, recipients);
+ } else {
+ Log.writeLog(this, this.toString(), "asap management storage not set - no propagation of channel creation");
+ }
+ }
+
+ public void createChannel(CharSequence urlTarget) throws IOException, ASAPException {
+ this.createChannel(urlTarget, (CharSequence) null);
+ }
+
+ @Override
+ public void createChannel(CharSequence urlTarget, CharSequence recipient) throws IOException, ASAPException {
+ Set recipients = new HashSet<>();
+ recipients.add(recipient);
+ this.createChannel(urlTarget, recipients);
+ }
+
+ private ASAPManagementStorage asapManagementStorage = null;
+ public void setASAPManagementStorage(ASAPManagementStorage asapManagementStorage) {
+ this.asapManagementStorage = asapManagementStorage;
+ }
+
+ public ASAPManagementStorage getASAPManagementStorage() throws IOException, ASAPException {
+ if(this.asapManagementStorage == null) {
+ throw new ASAPException("ASAP Management Storage not set");
+ }
+
+ return this.asapManagementStorage;
+ }
+
+ public boolean isASAPManagementStorageSet() {
+ return this.asapManagementStorage != null;
+ }
+
+ public void notifyChannelCreated(CharSequence appName, CharSequence owner,
+ CharSequence uri, Collection recipients)
+ throws ASAPException, IOException {
+
+ new ASAPManagementStorageImpl(this).notifyChannelCreated(appName, owner, uri, recipients);
+ }
+
+ public void addRecipient(CharSequence urlTarget, CharSequence recipient) throws IOException {
+ this.chunkStorage.getChunk(urlTarget, this.era).addRecipient(recipient);
+ }
+
+ public void setRecipients(CharSequence urlTarget, Collection recipients) throws IOException {
+ this.chunkStorage.getChunk(urlTarget, this.era).setRecipients(recipients);
+ }
+
+ public Set getRecipients(CharSequence urlTarget) throws IOException {
+ return this.chunkStorage.getChunk(urlTarget, this.era).getRecipients();
+ }
+
+ public void removeRecipient(CharSequence urlTarget, CharSequence recipient) throws IOException {
+ this.chunkStorage.getChunk(urlTarget, this.era).removeRecipient(recipient);
+ }
+
+ @Override
+ public void add(CharSequence uri, CharSequence message) throws IOException {
+ this.add(uri, message.toString().getBytes());
+ }
+
+ @Override
+ public void add(CharSequence uri, byte[] messageAsBytes) throws IOException {
+// Log.writeLog(this, this.toString(), "reached add(uri, byte[] message");
+ ASAPInternalChunk chunk = this.chunkStorage.getChunk(uri, this.era);
+
+// Log.writeLog(this, this.toString(), "call chunk.addMessage()");
+ chunk.addMessage(messageAsBytes);
+
+ // remember - something changed in that era
+ this.contentChanged();
+
+// Log.writeLog(this, this.toString(), "online?");
+ if(this.asapOnlineMessageSender != null) {
+ try {
+ Log.writeLog(this, this.toString(), "send online message...");
+ this.asapOnlineMessageSender.sendASAPAssimilateMessage(
+ this.format, uri, chunk.getRecipients(),
+ messageAsBytes, this.era);
+ } catch (IOException | ASAPException e) {
+ Log.writeLog(this, this.toString(),
+ "message written to local storage - but could not write to open asap connection: " +
+ e.getLocalizedMessage());
+ }
+ Log.writeLog(this, this.toString(), "... done sending online message");
+ } else {
+ Log.writeLog(this, this.toString(), "online sending not active");
+ }
+ }
+
+ private void contentChanged() throws IOException {
+ this.contentChanged = true;
+ Log.writeLog(this, this.toString(), "content changed - save status");
+ this.saveStatus();
+ }
+
+ private final ASAPChunkStorage chunkStorage;
+ protected String format = ASAP_1_0.ANY_FORMAT.toString();
+
+ @Override
+ public ASAPChunkStorage getChunkStorage() {
+ return this.chunkStorage;
+ }
+
+
+ @Override
+ public ASAPInternalChunk createNewChunk(String uri, int newEra) throws IOException {
+ ASAPInternalChunk chunk = this.getChunkStorage().getChunk(uri, newEra);
+ // set new era
+ this.newEra(true, newEra);
+ return chunk;
+ }
+
+ ASAPChunkStorage getStorage() {
+ return this.chunkStorage;
+ }
+
+ @Override
+ public void putExtra(CharSequence uri, String key, String value) throws IOException {
+ this.chunkStorage.getChunk(uri, this.era).putExtra(key, value);
+ }
+
+ @Override
+ public CharSequence removeExtra(CharSequence uri, String key) throws IOException {
+ return this.chunkStorage.getChunk(uri, this.era).removeExtra(key);
+ }
+
+ @Override
+ public CharSequence getExtra(CharSequence uri, String key) throws IOException {
+ return this.chunkStorage.getChunk(uri, this.era).getExtra(key);
+ }
+
+
+ public List getChannelURIs() throws IOException {
+ List uriList = new ArrayList<>();
+
+ List chunks = this.chunkStorage.getChunks(this.era);
+ for(ASAPInternalChunk chunk : chunks) {
+ uriList.add(chunk.getUri());
+ }
+
+ return uriList;
+ }
+
+ @Override
+ public ASAPChannel getChannel(CharSequence uri) throws ASAPException, IOException {
+ return this.getASAPChannelImpl(uri);
+ }
+
+ private ASAPChannelImpl getASAPChannelImpl(CharSequence uri) throws ASAPException, IOException {
+ if(this.channelExists(uri)) {
+ return new ASAPChannelImpl(this, uri);
+ }
+
+ throw new ASAPException("channel with this uri does not exist: " + uri);
+ }
+
+ @Override
+ public boolean channelExists(CharSequence uri) throws IOException {
+ return this.chunkStorage.existsChunk(uri, this.getEra());
+ }
+
+ public void removeChannel(CharSequence uri) throws IOException {
+ int currentEra;
+ int nextEra = this.getOldestEra();
+ do {
+ currentEra = nextEra;
+ ASAPInternalChunk chunk = this.chunkStorage.getChunk(uri, currentEra);
+ chunk.drop();
+ nextEra = ASAP.nextEra(currentEra);
+ } while(currentEra != this.getEra());
+ }
+
+ public ASAPMessages getChunkChain(int uriPosition) throws IOException, ASAPException {
+ return this.getChunkChain(uriPosition, this.era);
+ }
+
+ public ASAPMessages getChunkChain(CharSequence uri, int toEra) throws IOException {
+ return this.chunkStorage.getASAPMessages(uri, toEra);
+ }
+
+ public ASAPMessages getChunkChain(CharSequence uri) throws IOException {
+ return this.getChunkChain(uri, this.getEra());
+ }
+
+ public ASAPMessages getChunkChain(int uriPosition, int toEra)
+ throws IOException, ASAPException {
+
+ List channelURIs = this.getChannelURIs();
+ if(channelURIs.size() - 1 < uriPosition) {
+ throw new ASAPException("position greater than number of channels");
+ }
+
+ CharSequence uri = channelURIs.get(uriPosition);
+ if(uri == null) {
+ throw new ASAPException("uri at postion is null. Position: " + uriPosition);
+ }
+
+ return this.chunkStorage.getASAPMessages(uri, toEra);
+ }
+
+ //////////////////////////////////////////////////////////////////////
+ // ProtocolEngine //
+ //////////////////////////////////////////////////////////////////////
+
+ // extract those algorithms to another class (ASAPDefaultProtocolEngine) ?!
+ public void handleASAPAssimilate(ASAP_AssimilationPDU_1_0 asapAssimilationPDU, ASAP_1_0 protocolModem,
+ String encounteredPeer, InputStream is, OutputStream os, ASAPEncounterConnectionType connectionType,
+ ASAPChunkAssimilatedListener listener) throws ASAPException, IOException {
+
+ // before we start - lets crypto
+ if(!hasSufficientCrypto(asapAssimilationPDU)) return;
+
+ String senderE2E = asapAssimilationPDU.getSender();
+ int eraSender = asapAssimilationPDU.getEra();
+
+ // debug break
+ //if(PeerIDHelper.sameID(senderE2E, "Alice_42")) { int i = 42; }
+
+ if(PeerIDHelper.sameID(senderE2E, this.owner)) {
+ Log.writeLogErr(this, this.toString(), "I was offered messages from myself ("
+ + this.owner + ") by " + encounteredPeer + " - refused: ");
+ asapAssimilationPDU.takeDataFromStream();
+ return;
+ }
+
+ //<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>debug
+
+ boolean changed = false;
+ boolean allowedAssimilation = true;
+
+ ASAPInternalChunk incomingChunk = null;
+ MessagesContainer messagesContainer = null;
+ ASAPInMemoTransientMessages transientMessages = null;
+
+ ASAPHop lastHop = new ASAPHopImpl(encounteredPeer, asapAssimilationPDU.verified(),
+ asapAssimilationPDU.encrypted(), connectionType);
+
+ try {
+ if(eraSender != ASAP.TRANSIENT_ERA) {
+ incomingChunk = this.getIncomingChunk(encounteredPeer, asapAssimilationPDU);
+ messagesContainer = incomingChunk;
+ } else {
+ transientMessages =
+ new ASAPInMemoTransientMessages(asapAssimilationPDU, lastHop);
+
+ messagesContainer = transientMessages;
+ }
+ }
+ catch(ASAPException e) {
+ asapAssimilationPDU.takeDataFromStream();
+ throw e;
+ }
+
+ // put messages into container - incoming chunk or transient message container
+ List messageOffsets = asapAssimilationPDU.getMessageOffsets();
+
+ // iterate messages and stream into chunk
+ InputStream protocolInputStream = asapAssimilationPDU.getInputStream();
+ Log.writeLog(this, this.toString(), "take data to local chunk or transient message: " + messagesContainer);
+ this.streamReceivedMessages2Container(messagesContainer, protocolInputStream,
+ messageOffsets, asapAssimilationPDU.getLength());
+
+ // add entry to hop list
+ List asapHopList = asapAssimilationPDU.getASAPHopList();
+ Log.writeLog(this, this.toString(), "got hop list: " + asapHopList);
+
+ // add this new hop
+ asapHopList.add(lastHop);
+
+ // add hop list to newly create message container
+ messagesContainer.setASAPHopList(asapHopList);
+
+ ////////////////// write log
+ String uri = asapAssimilationPDU.getChannelUri();
+ // read all messages
+ //<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>debug
+
+ if(listener != null) {
+ if(eraSender != ASAP.TRANSIENT_ERA) {
+ listener.chunkStored(this.format,
+ senderE2E,
+ uri,
+ eraSender,
+ asapHopList
+ );
+ } else {
+ listener.transientMessagesReceived(transientMessages, lastHop);
+ }
+
+ } else {
+ Log.writeLog(this, this.toString(), "no chunk assimilated listener found");
+ }
+ }
+ private ASAPInternalChunk getIncomingChunk(String encounteredPeer, ASAP_AssimilationPDU_1_0 asapAssimilationPDU)
+ throws IOException, ASAPException {
+
+ Log.writeLog(this, this.toString(), "called: get incoming chunk");
+ String uri = asapAssimilationPDU.getChannelUri();
+ int eraSender = asapAssimilationPDU.getEra();
+ String senderE2E = asapAssimilationPDU.getSender();
+ ASAPInternalStorage incomingStorage = (ASAPInternalStorage) this.getIncomingStorage(senderE2E, true);
+ ASAPChunkStorage incomingChunkStorage = incomingStorage.getChunkStorage();
+ Log.writeLog(this, this.toString(), "got incoming chunk storage "
+ + incomingChunkStorage);
+
+ // get local target for data to come
+ if (!incomingChunkStorage.existsChunk(uri, eraSender)) {
+ ASAPInternalChunk localChunk = null;
+ // is there a local chunk - to clone recipients from?
+ if (this.channelExists(uri)) {
+ Log.writeLog(this, this.toString(), "get local chunk to copy channel data");
+ localChunk = incomingChunkStorage.getChunk(uri, this.getEra()); // get channel information
+ } else { // no information that can be copied
+ Log.writeLog(this, this.toString(), "asked to set up new channel: (uri/senderE2E): "
+ + uri + " | " + senderE2E);
+ // this channel is new to local peer - am I allowed to create it?
+ if (!this.securityAdministrator.allowedToCreateChannel(asapAssimilationPDU)) {
+ Log.writeLog(this, this.toString(),
+ ".. not allowed .. TODO not yet implemented .. always set up");
+
+ //allowedAssimilation = false; // TODO
+ } else {
+ Log.writeLog(this, this.toString(), "allowed. Set it up.");
+ this.createChannel(uri);
+ }
+ }
+ Log.writeLog(this, this.toString(), "create new chunk to assimilate received data");
+ ASAPInternalChunk incomingChunk = incomingStorage.createNewChunk(uri, eraSender);
+
+ if (localChunk != null) {
+ Log.writeLog(this, this.toString(), "copy local meta data into newly created incoming chunk");
+ incomingChunk.copyMetaData(this.getChannel(uri));
+ }
+ Log.writeLog(this, this.toString(), "new incoming chunk created: " + incomingChunk);
+ return incomingChunk;
+ } else {
+ // already exists. Add message if sender == originator and era last era of this channel
+ if(incomingStorage.getEra() == eraSender // era is current era
+ && PeerIDHelper.sameID(encounteredPeer, senderE2E) // E2E sender == P2P sender
+ ) {
+ Log.writeLog(this, this.toString(),
+ "received chunk exists but sender is originator and current era - message will be added: "
+ + senderE2E + " | " + eraSender + " | " + uri);
+
+ // finish routing...
+ if(incomingChunkStorage.getChunk(uri, eraSender).getASAPHopList().size() > 1) {
+ throw new ASAPException("chunk was already routed to me - met originator - will no overwrite chunk");
+ }
+
+ return incomingChunkStorage.getChunk(uri, eraSender);
+ } else {
+ // read assimilation message payload to oblivion!
+ throw new ASAPException("chunk that already exists; not current era or not originator: "
+ + senderE2E + " | " + eraSender + " | " + uri);
+ }
+ }
+ }
+
+ private void streamReceivedMessages2Container(MessagesContainer messagesContainer,
+ InputStream is, List messageOffsets, long totalLength) throws IOException {
+
+ long offset = 0;
+ for (long nextOffset : messageOffsets) {
+ //<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>debug
+
+ messagesContainer.addMessage(is, nextOffset - offset);
+ //if(!changed) { changed = true; this.contentChanged();}
+ offset = nextOffset;
+ }
+
+ // last round
+ //<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>debug
+
+ messagesContainer.addMessage(is, totalLength - offset);
+ }
+
+ private boolean hasSufficientCrypto(ASAP_PDU_1_0 pdu) {
+ if(this.getCryptoControl() == null) {
+ Log.writeLog(this, this.toString(), "crypto control set to allow anything");
+ return true;
+ }
+
+ boolean proceed = this.getCryptoControl().allowed2Process(pdu);
+ if(!proceed) {
+ Log.writeLog(this, this.toString(), "no sufficient crypto: " + pdu);
+ }
+
+ return proceed;
+ }
+
+ public void handleASAPInterest(ASAP_Interest_PDU_1_0 asapInterest, ASAP_1_0 protocol,
+ String encounteredPeer, OutputStream os, ASAPEncounterConnectionType connectionType)
+ throws ASAPException, IOException {
+
+ // before we start - lets crypto: TODO can be removed - do it on communication not engine level
+ if(!hasSufficientCrypto(asapInterest)) return;
+
+ // get remote peer
+ String senderID = asapInterest.getSender();
+
+ //<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>debug
+
+ // init
+ int workingEra = this.getOldestEra();
+
+ // already met?
+ if(this.lastSeen != null) {
+ Integer lastSeenEra = this.lastSeen.get(senderID);
+ if(lastSeenEra != null) workingEra = lastSeenEra;
+ }
+
+ // got even information from other side?
+ Map encounterMap = asapInterest.getEncounterMap();
+ Log.writeLog(this, this.toString(), "received encounterMap: " + encounterMap);
+
+ // am I in encounter list?
+ if(encounterMap != null) {
+ Integer eraEncounteredMe = encounterMap.get(this.owner);
+ if(eraEncounteredMe != null) {
+ int eraEncounter = eraEncounteredMe;
+ Log.writeLog(this, this.toString(), "found me in encounter map: " + encounterMap);
+ // would start with next era
+ eraEncounter = ASAP.nextEra(eraEncounter);
+ if (eraEncounter != workingEra && ASAP.isEraInRange(eraEncounter, this.getOldestEra(), workingEra)) {
+ // this seems to be a valid era - maybe got routed data
+ Log.writeLog(this, this.toString(),
+ "change 1st era from " + workingEra + " to " + eraEncounter);
+ workingEra = eraEncounter;
+ }
+ }
+ }
+
+ Log.writeLog(this, this.toString(), "transmit chunks from " + workingEra + " to era: " + this.era);
+
+ if(workingEra == this.era) {
+ // nothing todo
+ b = new StringBuilder();
+ b.append("there are no information before that era; ");
+ b.append("we only deliver information from previous eras - nothing todo here.");
+ Log.writeLog(this, this.toString(), b.toString());
+ } else {
+ // we iterate up to era just before current one - current one is active sync.
+ int lastEra = this.getPreviousEra(this.era);
+
+ //<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>debug
+
+ // make a breakpoint here
+ if (this.memento != null) this.memento.save(this);
+
+ this.sendChunks(this.owner, senderID, this.getChunkStorage(), protocol, workingEra, lastEra, os, true);
+ Log.writeLog(this, this.toString(), "ended iterating local chunks");
+ }
+
+ /////////////////////////////////// asap routing
+
+ if(this.routingAllowed()) {
+ // iterate: what sender do we know in our side?
+ for(CharSequence receivedFromID : this.getSender()) {
+ if(PeerIDHelper.sameID(encounteredPeer, receivedFromID)) {
+ // do not send messages back
+ continue;
+ }
+ Log.writeLog(this, this.toString(), "going to route messages from " + receivedFromID);
+ try {
+ ASAPStorage receivedMessagesStorage = this.getExistingIncomingStorage(receivedFromID);
+ int eraLastToSend = receivedMessagesStorage.getEra();
+ int eraFirstToSend = receivedMessagesStorage.getOldestEra();
+
+ // got encounter information from other peer?
+ if(encounterMap != null) {
+ Integer eraLastMet = encounterMap.get(receivedFromID);
+ if(eraLastMet != null) {
+ Log.writeLog(this, this.toString(),
+ "found sender received encounter map; last encounter: " + eraLastMet);
+ /*
+ Peer told us last encounter era - from senders perspective of course.
+ There are several options, sketch:
+
+ <------ our storage ------->
+ ............ [eraFirst] +++++++++++++++ [eraLast] .........
+ (a) (b) (c) (d)
+ a) We send everything we have
+ b) We send from b+1 until eraLast
+ c) + d) We are in sync or behind - nothing to do
+ */
+
+ // we would start with the next era
+ int eraAfterLastMet = ASAP.nextEra(eraLastMet);
+
+ if(ASAP.isEraInRange(eraAfterLastMet, eraFirstToSend, eraLastToSend)) { // case b)
+ eraFirstToSend = eraAfterLastMet;
+ }
+ }
+ }
+ this.sendChunks(receivedFromID, senderID, receivedMessagesStorage.getChunkStorage(), protocol,
+ eraFirstToSend, eraLastToSend, os,false);
+ }
+ catch(ASAPException e) {
+ Log.writeLogErr(this, this.toString(),
+ "internal problem: we know sender but cannot access its storage");
+ }
+ }
+ } else {
+ Log.writeLog(this, this.toString(), "engine does not send received chunks");
+ }
+ }
+
+ public boolean routingAllowed() {
+ return this.routingAllowed;
+ }
+
+ public void setBehaviourAllowRouting(boolean on) throws IOException {
+ this.routingAllowed = on;
+ this.saveStatus();
+ }
+
+ void sendInterest(CharSequence ownerID, ASAP_1_0 protocol, OutputStream os)
+ throws IOException, ASAPException {
+
+ Log.writeLog(this, this.toString(), "send interest for app/format: " + format);
+
+ // produce encounter map
+ Map encounterMap = new HashMap<>();
+
+ Set encounteredPeers = this.lastSeen.keySet();
+ for(String peerID : encounteredPeers) {
+ try {
+ int lastEra = this.getExistingIncomingStorage(peerID).getEra();
+ encounterMap.put(peerID, lastEra);
+ }
+ catch(ASAPException e) {
+ /*
+ There is no storage for encountered peer. Can happen - met but has not got anything from it.
+ So, take era from last seen...
+
+ I can't follow, sorry 2021, Dec, 10th (thsc42)
+ encounterMap.put(peerID, this.lastSeen.get(peerID));
+ */
+ }
+ }
+ Log.writeLog(this, this.toString(), "send encounterMap with interest: " + encounterMap);
+
+ protocol.interest(ownerID, null,
+ format, null, ASAP_1_0.ERA_NOT_DEFINED, ASAP_1_0.ERA_NOT_DEFINED,
+ os, this.getASAPCommunicationCryptoSettings().mustSign(),
+ this.getASAPCommunicationCryptoSettings().mustEncrypt(),
+ this.routingAllowed(),
+ encounterMap);
+ }
+
+ private void sendChunks(CharSequence sender, String encounteredPeer, ASAPChunkStorage chunkStorage,
+ ASAP_1_0 protocol, int workingEra,
+ int lastEra, OutputStream os, boolean remember) throws IOException, ASAPException {
+ Log.writeLog(this, this.toString(),
+ "sendChunks: sender: " + sender + " | encounteredPeer: " + encounteredPeer
+ + " | workingEra: " + workingEra);
+
+ /*
+ There is a little challenge: era uses a circle of numbers
+ We cannot say: higher number, later era. That rule does *not*
+ apply. We can calculate next era, though.
+
+ That loop has to be re-entered as long as working era has not
+ yet reached lastEra. In other words: lastRound is reached whenever
+ workingEra == lastEra. Processing lastEra is the last round
+ We at at least one round!
+ */
+
+ boolean lastRound = false; // assume more than one round
+ do {
+ lastRound = workingEra == lastEra;
+
+ List chunks = chunkStorage.getChunks(workingEra);
+ //<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>debug
+
+ for(ASAPInternalChunk chunk : chunks) {
+ boolean goAhead = true; // to avoid deep if-if-if-if structures
+
+ //<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>debug
+
+ if(chunk.getLength() < 1) {
+ goAhead = false;
+ }
+
+ // is not a public chunk
+ if (goAhead && !this.isPublic(chunk)) {
+ Set recipients = chunk.getRecipients();
+ if (recipients == null || !recipients.contains(encounteredPeer)) {
+ goAhead = false;
+ }
+ }
+
+ if (goAhead) {
+ Log.writeLog(this, this.toString(), "send chunk");
+ protocol.assimilate(sender, // owner or source from received message
+ encounteredPeer, // peer to which we are connected right now
+ this.format,
+ chunk.getUri(), // channel ok
+ workingEra, // era ok
+ chunk.getLength(), // data length
+ chunk.getOffsetList(),
+ chunk.getASAPHopList(),
+ chunk.getMessageInputStream(),
+ os,
+ this.getASAPCommunicationCryptoSettings());
+
+ // remember sent
+ if(remember) chunk.deliveredTo(encounteredPeer);
+ Log.writeLog(this, this.toString(), "remembered delivered to " + encounteredPeer);
+
+ //>>>>>>>>>>>>>>>>>>>debug
+ // sent to all recipients
+ if (chunk.getRecipients().size() == chunk.getDeliveredTo().size()) {
+ Log.writeLog(this, this.toString(),
+ "#recipients == #deliveredTo chunk delivered to any potential remotePeer - could drop it");
+ if (this.isDropDeliveredChunks()) {
+ chunk.drop();
+ Log.writeLog(this, this.toString(), "chunk dropped");
+ } else {
+ Log.writeLog(this, this.toString(),
+ "drop flag set false - engine does not remove delivered chunks");
+ }
+ }
+ } else {
+ Log.writeLog(this, this.toString(), "nothing sent: empty or not on recipient list");
+ }
+ }
+
+ if(remember) {
+ // remember that we are in sync until that era
+ this.setLastSeen(encounteredPeer, workingEra);
+
+ // make a breakpoint here
+ if (this.memento != null) this.memento.save(this);
+ }
+
+ // next era which isn't necessarily workingEra++
+ workingEra = this.getNextEra(workingEra);
+
+ // as long as not already performed last round
+ } while(!lastRound);
+ }
+
+ private boolean isDropDeliveredChunks() {
+ return this.dropDeliveredChunks;
+ }
+
+ public void setBehaviourDropDeliveredChunks(boolean drop) throws IOException {
+ this.dropDeliveredChunks = drop;
+ this.saveStatus();
+ }
+
+ @Override
+ public int getNextEra(int workingEra) {
+ return ASAP.nextEra(workingEra);
+ }
+
+ @Override
+ public int getPreviousEra(int workingEra) {
+ return ASAP.previousEra(workingEra);
+ }
+
+ private int getEraStartSync(String peer) {
+ Integer lastEra = this.lastSeen.get(peer);
+ if(lastEra == null) {
+ return this.getOldestEra();
+ }
+
+ return lastEra;
+ }
+
+ private void setLastSeen(String peer, int workingEra) {
+ this.lastSeen.put(peer, era);
+ }
+
+ @Override
+ public int getOldestEra() {
+ return this.oldestEra;
+ }
+
+ @Override
+ public int getEra() {
+ return this.era;
+ }
+
+ @Override
+ public CharSequence getFormat() {
+ return this.format;
+ }
+
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // Online management //
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ public void activateOnlineMessages(ASAPInternalPeer multiEngine) {
+ if(this.asapOnlineMessageSender == null) {
+ Log.writeLog(this, this.toString(),
+ "(" + this.format + ") created new online message sender");
+ this.attachASAPMessageAddListener(new ASAPOnlineMessageSenderEngineSide(multiEngine));
+ } else {
+ Log.writeLog(this, this.toString(),
+ "(" + this.format + ") online message sender already running");
+ }
+ }
+
+ public void deactivateOnlineMessages() {
+ this.detachASAPMessageAddListener();
+ }
+}
diff --git a/src/net/sharksystem/asap/ASAPEngineFS.java b/src/main/java/net/sharksystem/asap/engine/ASAPEngineFS.java
similarity index 56%
rename from src/net/sharksystem/asap/ASAPEngineFS.java
rename to src/main/java/net/sharksystem/asap/engine/ASAPEngineFS.java
index 2e5b811..142a4fa 100644
--- a/src/net/sharksystem/asap/ASAPEngineFS.java
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPEngineFS.java
@@ -1,6 +1,10 @@
-package net.sharksystem.asap;
+package net.sharksystem.asap.engine;
+import net.sharksystem.asap.ASAPChannel;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPChunkStorage;
import net.sharksystem.asap.protocol.ASAP_1_0;
+import net.sharksystem.utils.Log;
import java.io.File;
import java.io.IOException;
@@ -18,8 +22,7 @@ public class ASAPEngineFS extends ASAPEngine {
public static final String DEFAULT_ROOT_FOLDER_NAME = "SHARKSYSTEM_ASAP";
- private ASAPEngineFS(String owner,
- String rootDirectory, ASAPChunkStorageFS chunkStorage, CharSequence format)
+ private ASAPEngineFS(String owner, String rootDirectory, CharSequence format)
throws ASAPException, IOException {
super(new ASAPChunkStorageFS(rootDirectory, format.toString()), format);
@@ -28,6 +31,24 @@ private ASAPEngineFS(String owner,
this.rootDirectory = rootDirectory;
}
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("owner: ");
+ sb.append(this.getOwner());
+ sb.append(" | oldestEra: ");
+ sb.append(this.getOldestEra());
+ sb.append(" | era: ");
+ sb.append(this.getEra());
+ sb.append(" | routing: ");
+ sb.append(this.routingAllowed());
+ /*
+ sb.append(" | rootFolder: ");
+ sb.append(this.rootDirectory);
+ */
+
+ return sb.toString();
+ }
+
public String getRootFolder() {
return this.rootDirectory;
}
@@ -70,35 +91,61 @@ public static ASAPEngine getASAPEngine(String owner, String rootDirectory, CharS
return ASAPEngineFS.getASAPEngineFS(owner, rootDirectory, format);
}
- public ASAPStorage refresh() throws IOException, ASAPException {
+ public ASAPInternalStorage refresh() throws IOException, ASAPException {
this.memento.save(this);
return ASAPEngineFS.getExistingASAPEngineFS(this.rootDirectory);
}
- /**
- *
- * @param owner can be null - restored
- * @param rootDirectory must not be null
- * @param format can be null - restored
- * @return
- * @throws IOException
- * @throws ASAPException
- */
+ public void setOldestEra(int oldestEra) throws IOException {
+ this.oldestEra = oldestEra;
+ this.saveMemento();
+ }
+
+ private void saveMemento() throws IOException {
+ this.getMemento(this.rootDirectory).save(this);
+ }
+
static ASAPEngineFS getASAPEngineFS(String owner, String rootDirectory, CharSequence format)
throws IOException, ASAPException {
+ return ASAPEngineFS.getASAPEngineFS(owner, rootDirectory, format, false);
+ }
+
+ /**
+ *
+ * @param owner can be null - restored
+ * @param rootDirectory must not be null
+ * @param format can be null - restored
+ * @return
+ * @throws IOException
+ * @throws ASAPException
+ */
+ static ASAPEngineFS getASAPEngineFS(String owner, String rootDirectory, CharSequence format, boolean createFolder)
+ throws IOException, ASAPException {
// root directory must exist when setting up an engine
File root = new File(rootDirectory);
if(!root.exists() || !root.isDirectory()) {
- throw new ASAPException("chunk root directory must exist when creating an ASAPEngine");
+ if(!createFolder) {
+ throw new ASAPException("chunk root directory must exist when creating an ASAPEngine: " + rootDirectory);
+ } else {
+ root.mkdirs();
+ }
+ }
+
+ if(format == null || format.toString().equalsIgnoreCase(ASAP_1_0.ANY_FORMAT)) {
+ ASAPMementoFS asapMementoFS = new ASAPMementoFS(root);
+ asapMementoFS.read();
+ format = asapMementoFS.getFormat();
}
String formatString = format != null ? format.toString() : ASAP_1_0.ANY_FORMAT;
ASAPEngineFS engine = new ASAPEngineFS(
owner,
- rootDirectory,
- new ASAPChunkStorageFS(rootDirectory, formatString),
- ASAP_1_0.ANY_FORMAT // set to default - real value is restored by memento anyway
+ rootDirectory,
+// new ASAPChunkStorageFS(rootDirectory, formatString),
+// ASAP_1_0.ANY_FORMAT // set to default - real value is restored by memento anyway
+ formatString
+
);
@@ -120,18 +167,6 @@ static ASAPEngineFS getASAPEngineFS(String owner, String rootDirectory, CharSequ
}
}
- // reset owner?
- if(owner != null && engine.owner != null
- && !engine.owner.equalsIgnoreCase(ANONYMOUS_OWNER)
- && !engine.owner.equalsIgnoreCase(DEFAULT_OWNER)
- && !owner.equalsIgnoreCase(ANONYMOUS_OWNER)
- && !owner.equalsIgnoreCase(DEFAULT_OWNER)
- && !owner.equalsIgnoreCase(engine.owner)) {
-
- throw new ASAPException("cannot overwrite folder of a "
- + "non-anonymous but different owner: " + engine.owner);
- }
-
// replacing owner could be done
if(owner != null
&& !owner.equalsIgnoreCase(ANONYMOUS_OWNER)
@@ -154,13 +189,25 @@ private void restoreFromMemento() throws IOException {
}
+ void syncMemento() throws IOException {
+ ASAPMementoFS asapMementoFS = new ASAPMementoFS(new File(this.rootDirectory));
+ asapMementoFS.read();
+// Log.writeLog(this, this.toString(), "read memento: " + asapMementoFS);
+// Log.writeLog(this, this.toString(), "this.lastwritten: " + this.lastMementoWritten);
+
+ if(asapMementoFS.lastMementoWritten != this.lastMementoWritten) {
+// Log.writeLog(this, this.toString(),"restore from memento - out of sync");
+ this.restoreFromMemento();
+ }
+ }
+
@Override
- public void add(CharSequence urlTarget, byte[] messageAsBytes) throws IOException {
+ public void add(CharSequence uri, byte[] messageAsBytes) throws IOException {
// always re-read metainformation
this.restoreFromMemento();
// do the real work
- super.add(urlTarget, messageAsBytes);
+ super.add(uri, messageAsBytes);
}
/*
@@ -170,7 +217,7 @@ public static ASAPEngine getASAPEngine(String rootDirectory, CharSequence format
return ASAPEngineFS.getASAPEngine(null, rootDirectory, format);
}*/
-
+
private ASAPMementoFS getMemento(String rootDirectory) {
return new ASAPMementoFS(new File(rootDirectory));
}
@@ -178,14 +225,44 @@ private ASAPMementoFS getMemento(String rootDirectory) {
private HashMap storageList = new HashMap<>();
@Override
- public ASAPChunkStorage getIncomingChunkStorage(CharSequence sender) {
+ public ASAPChunkStorage getReceivedChunksStorage(CharSequence sender) {
String dir = this.rootDirectory + "/" + sender;
- return new ASAPChunkStorageFS(dir, this.format);
+ return new ASAPChunkStorageFS(dir, this.format, this.era);
}
- public ASAPStorage getExistingIncomingStorage(CharSequence sender) throws IOException, ASAPException {
- String dir = this.rootDirectory + "/" + sender;
- return ASAPEngineFS.getExistingASAPEngineFS(dir);
+ public ASAPInternalStorage getIncomingStorage(CharSequence sender, boolean create) throws IOException, ASAPException {
+ return ASAPEngineFS.getASAPEngineFS(
+ sender.toString(), // becomes owner
+ this.rootDirectory + "/" + sender, // folder
+ this.getFormat(), // format taken from superior storage
+ create);
+ }
+
+ public ASAPInternalStorage getExistingIncomingStorage(CharSequence sender) throws IOException, ASAPException {
+ return this.getIncomingStorage(sender, true);
+ }
+
+ /**
+ * Backdoor - for tests only - create an incoming storage
+ * @param sender
+ * @return
+ * @throws IOException
+ * @throws ASAPException
+ */
+ public ASAPInternalStorage getIncomingStorage(CharSequence sender) throws IOException, ASAPException {
+ return this.getIncomingStorage(sender, true);
+ /*
+ String folderName = this.rootDirectory + "/" + sender;
+ File folder = new File(folderName);
+ if(!folder.exists()) {
+ folder.mkdirs();
+ }
+
+ return ASAPEngineFS.getASAPEngineFS(
+ sender.toString(), // becomes owner
+ folderName, // folder
+ this.getFormat()); // format taken from superior storage
+ */
}
@Override
@@ -216,34 +293,4 @@ public List getSender() {
return senderList;
}
-
- ////////////////////////////////////////////////////////////////////////////////////////
- // helper //
- ////////////////////////////////////////////////////////////////////////////////////////
-
- public static void removeFolder(String eraPathName) {
- File dir = new File(eraPathName);
-
- String[] dirEntries = dir.list();
-
- if(dirEntries != null) {
- for(String fileName : dirEntries) {
- File fileInDir = new File(eraPathName + "/" + fileName);
- if(fileInDir.isDirectory()) {
- ASAPEngineFS.removeFolder(fileInDir.getAbsolutePath());
- } else {
- try {
- if(!fileInDir.delete()) {
- System.out.println("ASAPEngineFS: cannot delete file (try deleteOnExit):" + fileInDir);
- }
- } catch (RuntimeException e) {
- System.err.println("ASAPEngineFS: cannot file:" + e.getLocalizedMessage());
- // try next
- }
- }
- }
- }
-
- dir.delete();
- }
}
diff --git a/src/net/sharksystem/asap/ASAPEngineFSSetting.java b/src/main/java/net/sharksystem/asap/engine/ASAPEngineFSSetting.java
similarity index 63%
rename from src/net/sharksystem/asap/ASAPEngineFSSetting.java
rename to src/main/java/net/sharksystem/asap/engine/ASAPEngineFSSetting.java
index dd7f13f..f2fe8cf 100644
--- a/src/net/sharksystem/asap/ASAPEngineFSSetting.java
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPEngineFSSetting.java
@@ -1,12 +1,12 @@
-package net.sharksystem.asap;
+package net.sharksystem.asap.engine;
public class ASAPEngineFSSetting {
final CharSequence folder;
final CharSequence format;
- final ASAPChunkReceivedListener listener;
+ final ASAPChunkAssimilatedListener listener;
public ASAPEngineFSSetting(CharSequence format, CharSequence folder,
- ASAPChunkReceivedListener listener) {
+ ASAPChunkAssimilatedListener listener) {
this.format = format;
this.folder = folder;
this.listener = listener;
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPEnginePermissionSettings.java b/src/main/java/net/sharksystem/asap/engine/ASAPEnginePermissionSettings.java
new file mode 100644
index 0000000..2679c4e
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPEnginePermissionSettings.java
@@ -0,0 +1,54 @@
+package net.sharksystem.asap.engine;
+
+import java.io.IOException;
+
+interface ASAPEnginePermissionSettings {
+ /**
+ * Engine can remember peers they encountered. It is assumed that those peers are kept with the local peer (not only
+ * in this engine)
+ * @param on
+ * @throws IOException
+ */
+ void setRememberEncounteredPeers(boolean on) throws IOException;
+
+ /**
+ * Engine would ignore all unencrypted messages if set true.
+ * @param on
+ * @throws IOException
+ */
+ void setReceivedMessagesMustBeEncrypted(boolean on) throws IOException;
+
+ /**
+ * Engine would ignore all unsigned messages if set true.
+ * @param on
+ * @throws IOException
+ */
+ void setReceivedMessagesMustBeSigned(boolean on) throws IOException;
+
+ /**
+ * Define with what peers an engine is allowed to communicate
+ * @param safetyLevel
+ * @throws IOException
+ */
+ void setSetAllowedRemotePeers(AllowedRemotePeers safetyLevel);
+
+ public enum AllowedRemotePeers {
+ ANY_PEER /** no restrictions - allowed to communicate with any peer */,
+ PEERS_MET /** allowed to communicate with already encountered peers */,
+ PEERS_VERIFIED /** allowed to communicate with peers who can be verified with a certificate */;
+ }
+
+ /**
+ * Engine is allowed to reveal its supported format or not
+ * @param peerName can be null for anonymous peer
+ * @return
+ */
+ boolean setRevealEngineFormat(String peerName);
+
+ /**
+ * Engine is allowed to send open (messages with no recipient specified) messages to a peer
+ * @param peerName can be null for anonymous peer
+ * @return
+ */
+ boolean setSendOpenMessages(String peerName);
+}
diff --git a/src/net/sharksystem/asap/ASAPInMemoMessages.java b/src/main/java/net/sharksystem/asap/engine/ASAPInMemoMessages.java
similarity index 70%
rename from src/net/sharksystem/asap/ASAPInMemoMessages.java
rename to src/main/java/net/sharksystem/asap/engine/ASAPInMemoMessages.java
index aee3da7..7162d0b 100644
--- a/src/net/sharksystem/asap/ASAPInMemoMessages.java
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPInMemoMessages.java
@@ -1,13 +1,13 @@
-package net.sharksystem.asap;
+package net.sharksystem.asap.engine;
-import net.sharksystem.asap.apps.ASAPMessages;
-import sun.reflect.generics.reflectiveObjects.NotImplementedException;
+import net.sharksystem.asap.ASAPUtils;
+import net.sharksystem.utils.Utils;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPMessages;
+import net.sharksystem.utils.Log;
import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
+import java.util.*;
/**
* @author thsc
@@ -20,10 +20,10 @@ class ASAPInMemoMessages implements ASAPMessages {
private final int toEra;
private final String format;
- private List chunkList;
+ private List chunkList;
/** the internal message Cache */
- private List messageCache;
+ private List messageCache;
private int firstIndexMessageCache = -1;
private int lastIndexMessageCache = -1;
private int maxCacheLen;
@@ -39,6 +39,17 @@ public ASAPInMemoMessages(ASAPChunkStorageFS chunkStorage,
this.fromEra = fromEra;
this.toEra = toEra;
this.maxCacheLen = maxCacheLen;
+
+ Log.writeLog(this, this.toString());
+ }
+
+ public String toString() {
+ return "format: "
+ + format
+ + " | uri: " + uri
+ + " | fromEra: " + fromEra
+ + " | toEra: " + toEra
+ + " | rootDir: " + chunkStorage.getRootDirectory();
}
public ASAPInMemoMessages(ASAPChunkStorageFS chunkStorage,
@@ -55,40 +66,53 @@ private void initialize() throws IOException {
this.initialized = true;
}
}
-
+
private void syncChunkList() throws IOException {
// get all chunks in chronological order
-
+ Collection erasInFolder = Utils.getErasInFolder(this.chunkStorage.getRootDirectory());
+ if(erasInFolder.isEmpty()) return;
+
+ Collection erasToUse = ASAPUtils.getErasInRange(erasInFolder, this.fromEra, this.toEra);
+ if(erasToUse.isEmpty()) return;
+
+ /*
// current era in following loop
int thisEra = this.fromEra;
-
+
// do we need more than one loop?
boolean anotherLoop = this.fromEra != this.toEra;
// are we in the final loop?
boolean finalLoop = !anotherLoop;
+ */
- // drop old vunk list - if any
+ // drop old chunk list - if any
this.chunkList = new ArrayList<>();
- do {
+// do {
+ for(Integer thisEra : erasToUse) {
// check if chunk exists - don't create on
- if(this.chunkStorage.existsChunk(this.uri, thisEra)) {
+ Log.writeLog(this, "reached era: " + thisEra);
+ if (erasInFolder.contains(thisEra) && this.chunkStorage.existsChunk(this.uri, thisEra)) {
// is there - get it
- ASAPChunk chunk = this.chunkStorage.getChunk(this.uri, thisEra);
+ Log.writeLog(this, "getChunk with era: " + thisEra);
+ ASAPInternalChunk chunk = this.chunkStorage.getChunk(this.uri, thisEra);
this.chunkList.add(chunk);
this.numberOfMessages += chunk.getNumberMessage();
}
+ /*
if (anotherLoop) {
if (finalLoop) {
anotherLoop = false;
} else {
- thisEra = ASAPEngine.nextEra(thisEra);
+ thisEra = ASAP.nextEra(thisEra);
finalLoop = thisEra == this.toEra;
}
}
} while (anotherLoop);
+ */
+ }
}
public int size() throws IOException {
@@ -106,7 +130,6 @@ public CharSequence getFormat() {
return this.format;
}
- @Override
public Iterator getMessagesAsCharSequence() throws IOException {
this.initialize();
@@ -121,13 +144,44 @@ public Iterator getMessages() throws IOException {
}
@Override
- public CharSequence getMessage(int position, boolean chronologically)
+ public CharSequence getMessageAsCharSequence(int position, boolean chronologically) throws ASAPException, IOException {
+ return new String(this.getMessage(position, chronologically));
+ }
+
+ public ASAPInternalChunk getChunk(int position, boolean chronologically) throws IOException, ASAPException {
+ this.initialize();
+
+ if(position >= this.numberOfMessages)
+ throw new ASAPException("Position reaches beyond total number of messages in this chunk (is it even empty?)");
+
+ if(!chronologically) {
+ // invert position - first becomes last etc.
+ position = this.numberOfMessages - 1 - position;
+ }
+
+ ASAPInternalChunk foundChunk = null;
+ // find chunk
+ for(ASAPInternalChunk chunk : this.chunkList) {
+ if(position < chunk.getNumberMessage()) {
+ foundChunk = chunk;
+ break;
+ }
+
+ position -= chunk.getNumberMessage();
+ }
+
+ if(foundChunk == null) throw new ASAPException("cannot find chunk for position - looks like a bug");
+ return foundChunk;
+ }
+
+ @Override
+ public byte[] getMessage(int position, boolean chronologically)
throws ASAPException, IOException {
this.initialize();
if(position >= this.numberOfMessages)
- throw new ASAPException("Position exceeds number of message");
+ throw new ASAPException("Position reaches beyond total number of messages in this chunk (is it even empty?)");
if(!chronologically) {
// invert position - first becomes last etc.
@@ -135,7 +189,7 @@ public CharSequence getMessage(int position, boolean chronologically)
}
if(this.messageCache != null && position >= this.firstIndexMessageCache && position <= this.lastIndexMessageCache) {
- return this.messageCache.get(position - this.firstIndexMessageCache); // TODO calculation correct?
+ return this.messageCache.get(position - this.firstIndexMessageCache);
}
// not yet in cache - find chunk with required message
@@ -143,10 +197,10 @@ public CharSequence getMessage(int position, boolean chronologically)
int lastIndex = 0; // absolut index of last message in current chunk
boolean found = false;
- ASAPChunk fittingChunk = null;
+ ASAPInternalChunk fittingChunk = null;
int fittingChunkIndex = 0;
- for(ASAPChunk chunk : this.chunkList) {
+ for(ASAPInternalChunk chunk : this.chunkList) {
lastIndex = firstIndex + chunk.getNumberMessage() - 1;
if(position >= firstIndex && position <= lastIndex) {
@@ -172,7 +226,8 @@ public CharSequence getMessage(int position, boolean chronologically)
// simple approach in that first implementation ... we keep fitting chunk in memory
/////////////////////////////////////////////////////////////////
- Iterator messages = fittingChunk.getMessages();
+// Iterator messages = fittingChunk.getMessagesAsCharSequence();
+ Iterator messages = fittingChunk.getMessages();
// chunk bigger than max cache size?
int chunkSize = fittingChunk.getNumberMessage();
@@ -235,13 +290,13 @@ public void sync() throws IOException {
//////////////////////////////////////////////////////////////////////////////////////////
private abstract class ChunkListIterator {
- private final List chunkList;
- private ASAPChunk currentChunk;
+ private final List chunkList;
+ private ASAPInternalChunk currentChunk;
private int nextIndex;
private Iterator currentIterator;
private T messageAhead;
- public ChunkListIterator(List chunkList) throws IOException {
+ public ChunkListIterator(List chunkList) throws IOException {
this.chunkList = chunkList;
this.currentChunk = null;
this.nextIndex = 0;
@@ -296,20 +351,20 @@ public T next() {
return retMessage;
}
- abstract Iterator getMessageIterator(ASAPChunk chunk) throws IOException;
+ abstract Iterator getMessageIterator(ASAPInternalChunk chunk) throws IOException;
}
private class ChunkListMessageIterator extends ChunkListIterator implements Iterator {
private Iterator currentIterator;
private CharSequence messageAhead;
- public ChunkListMessageIterator(List chunkList) throws IOException {
+ public ChunkListMessageIterator(List chunkList) throws IOException {
super(chunkList);
}
@Override
- Iterator getMessageIterator(ASAPChunk chunk) throws IOException {
- return chunk.getMessages();
+ Iterator getMessageIterator(ASAPInternalChunk chunk) throws IOException {
+ return chunk.getMessagesAsCharSequence();
}
}
@@ -317,13 +372,13 @@ private class ChunkListByteMessageIterator extends ChunkListIterator imp
private Iterator currentIterator;
private CharSequence messageAhead;
- public ChunkListByteMessageIterator(List chunkList) throws IOException {
+ public ChunkListByteMessageIterator(List chunkList) throws IOException {
super(chunkList);
}
@Override
- Iterator getMessageIterator(ASAPChunk chunk) throws IOException {
- return chunk.getMessagesAsBytes();
+ Iterator getMessageIterator(ASAPInternalChunk chunk) throws IOException {
+ return chunk.getMessages();
}
}
}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPInMemoTransientMessages.java b/src/main/java/net/sharksystem/asap/engine/ASAPInMemoTransientMessages.java
new file mode 100644
index 0000000..10d1642
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPInMemoTransientMessages.java
@@ -0,0 +1,101 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.*;
+import net.sharksystem.asap.protocol.ASAP_AssimilationPDU_1_0;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+public class ASAPInMemoTransientMessages implements ASAPMessages, MessagesContainer {
+ private final CharSequence format;
+ private final CharSequence uri;
+ private final CharSequence sender;
+ private ASAPHop asapHop;
+ private int size = -1;
+ private List messageList = new ArrayList<>();
+
+ ASAPInMemoTransientMessages(ASAP_AssimilationPDU_1_0 pdu, ASAPHop asapHop) {
+ this.format = pdu.getFormat();
+ this.uri = pdu.getChannelUri();
+ this.sender = pdu.getSender();
+ this.asapHop = asapHop;
+ }
+
+ public ASAPInMemoTransientMessages(CharSequence format, CharSequence uri, CharSequence sender, ASAPHop asapHop) {
+ this.format = format;
+ this.uri = uri;
+ this.sender = sender;
+ this.asapHop = asapHop;
+ }
+
+ @Override
+ public int size() throws IOException {
+ return this.messageList.size();
+ }
+
+ @Override
+ public CharSequence getURI() {
+ return this.uri;
+ }
+
+ @Override
+ public CharSequence getFormat() {
+ return this.format;
+ }
+
+ public CharSequence getSender() { return this.sender; }
+
+ @Override
+ public void setASAPHopList(List asapHopList) throws IOException {
+ if(this.asapHop == null) {
+ this.asapHop = asapHopList.get(asapHopList.size()-1);
+ }
+ }
+
+ @Override
+ public Iterator getMessagesAsCharSequence() throws IOException {
+ throw new IOException("not implemented yet");
+ }
+
+ @Override
+ public Iterator getMessages() throws IOException {
+ return this.messageList.iterator();
+ }
+
+ @Override
+ public CharSequence getMessageAsCharSequence(int position, boolean chronologically) throws ASAPException, IOException {
+ return new String(this.getMessage(position, chronologically));
+ }
+
+ @Override
+ public byte[] getMessage(int position, boolean chronologically) throws ASAPException, IOException {
+ if(position > this.messageList.size() || position < 0)
+ throw new ASAPException("no message on index (out of range): " + position);
+
+ int index = chronologically ? position : this.messageList.size() - position;
+
+ return this.messageList.get(index);
+ }
+
+ @Override
+ public ASAPChunk getChunk(int position, boolean chronologically) throws IOException, ASAPException {
+ throw new ASAPException("transient message are not stored");
+ }
+
+ @Override
+ public void addMessage(InputStream is, long length) throws IOException {
+ if(length > Integer.MAX_VALUE) throw new IOException("length exceeds range of integer value");
+
+ byte[] message = new byte[(int)length];
+ is.read(message);
+
+ this.addMessage(message);
+ }
+
+ public void addMessage(byte[] message) throws IOException {
+ this.messageList.add(message);
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPInternalChunk.java b/src/main/java/net/sharksystem/asap/engine/ASAPInternalChunk.java
new file mode 100644
index 0000000..39c794e
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPInternalChunk.java
@@ -0,0 +1,85 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.ASAPChannel;
+import net.sharksystem.asap.ASAPChunk;
+import net.sharksystem.asap.ASAPHop;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.*;
+
+/**
+ * An ASAP chunk is a set of message with the same format, same uri and same era.
+ *
+ * Reading from a chunk can be done anytime.
+ *
+ * Use change methods only if you really know what you do. Most likely, there will be
+ * a running ASAP protocol in the background that writes data into chunks, namely chunks
+ * of current era. The protocol engine reads also from older era to transmit messages to
+ * encountered peers. There will be a documentation that explains strategies when to do what.
+ *
+ * Rule of thumb: Read is ok. Better do not change anything with this interface.
+ *
+ * @author thsc
+ */
+public interface ASAPInternalChunk extends ASAPChunk, MessagesContainer {
+ /**
+ * Convenient methode: It calls getMessages and transforms each message into a string
+ * @return iterator of all messages in the chunk
+ * @throws IOException
+ */
+ Iterator getMessagesAsCharSequence() throws IOException;
+
+ /**
+ *
+ * @return recipients of that chunk
+ */
+ Set getRecipients();
+
+ /**
+ * add recipients
+ * @param recipient
+ * @throws IOException
+ */
+ void addRecipient(CharSequence recipient) throws IOException;
+
+ /**
+ * set a list of recipients. Former recipients are dikscarded
+ * @param recipients
+ * @throws IOException
+ */
+ void setRecipients(Collection recipients) throws IOException;
+
+ /**
+ * recipient is removed
+ * @param recipients
+ * @throws IOException
+ */
+ void removeRecipient(CharSequence recipients) throws IOException;
+
+ long getLength();
+
+ List getOffsetList();
+
+ InputStream getMessageInputStream();
+
+ void putExtra(String key, String value) throws IOException;
+
+ CharSequence removeExtra(String key) throws IOException;
+
+ CharSequence getExtra(String key) throws IOException;
+
+ /**
+ * set up this chunk by a source
+ * @param chunkSource
+ */
+ void clone(ASAPInternalChunk chunkSource) throws IOException;
+
+ HashMap getExtraData();
+
+ void deliveredTo(String peer) throws IOException;
+
+ List getDeliveredTo();
+
+ void copyMetaData(ASAPChannel channel) throws IOException;
+}
diff --git a/src/net/sharksystem/asap/ASAPChunkFS.java b/src/main/java/net/sharksystem/asap/engine/ASAPInternalChunkFS.java
similarity index 57%
rename from src/net/sharksystem/asap/ASAPChunkFS.java
rename to src/main/java/net/sharksystem/asap/engine/ASAPInternalChunkFS.java
index e57737b..7e57eaa 100644
--- a/src/net/sharksystem/asap/ASAPChunkFS.java
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPInternalChunkFS.java
@@ -1,6 +1,12 @@
-package net.sharksystem.asap;
+package net.sharksystem.asap.engine;
-import net.sharksystem.asap.util.Helper;
+import net.sharksystem.asap.ASAPChannel;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPHop;
+import net.sharksystem.asap.utils.ASAPSerialization;
+import net.sharksystem.asap.utils.ASAPLogHelper;
+import net.sharksystem.utils.Log;
+import net.sharksystem.utils.SerializationHelper;
import java.io.*;
import java.util.*;
@@ -9,7 +15,7 @@
*
* @author thsc
*/
-class ASAPChunkFS implements ASAPChunk {
+public class ASAPInternalChunkFS implements ASAPInternalChunk {
public static final String META_DATA_EXTENSION = "meta";
public static final String DATA_EXTENSION = "content";
public static final String DEFAULT_URL = "content://sharksystem.net/noContext";
@@ -21,6 +27,8 @@ class ASAPChunkFS implements ASAPChunk {
private List messageStartOffsets = new ArrayList<>();
private File metaFile;
private File messageFile;
+
+ private List hopList;
private int era;
@@ -28,7 +36,11 @@ class ASAPChunkFS implements ASAPChunk {
@Override
- public void clone(ASAPChunk chunkSource) throws IOException {
+ public void clone(ASAPInternalChunk chunkSource) throws IOException {
+ if(metaFile.getAbsolutePath().contains("ultihopTests/Alice_42/1/sha")) {
+ Log.writeLog(this, this.toString(), "DEBUGGING_Multihop_Bug #2: " + metaFile.exists());
+ }
+
this.uri = chunkSource.getUri();
this.recipients = chunkSource.getRecipients();
this.extraData = chunkSource.getExtraData();
@@ -45,6 +57,16 @@ public void copyMetaData(ASAPChannel channel) throws IOException {
this.saveStatus();
}
+ @Override
+ public List getASAPHopList() {
+ return this.hopList;
+ }
+
+ public void setASAPHopList(List asapHopList) throws IOException {
+ this.hopList = asapHopList;
+ this.saveStatus();
+ }
+
public HashMap getExtraData() {
return this.extraData;
}
@@ -60,27 +82,28 @@ public List getDeliveredTo() {
return this.deliveredTo;
}
- ASAPChunkFS(ASAPChunkStorageFS storage, String targetUri, int era) throws IOException {
- this(storage, targetUri, era, null);
+ ASAPInternalChunkFS(ASAPChunkStorageFS storage, String uri, int era) throws IOException {
+ this(storage, uri, era, null);
}
- ASAPChunkFS(ASAPChunkStorageFS storage, String targetUri, int era, String sender) throws IOException {
+ ASAPInternalChunkFS(ASAPChunkStorageFS storage, String uri, int era, String sender) throws IOException {
this.storage = storage;
- if(targetUri != null) {
- this.uri = targetUri;
+ if(uri != null) {
+ this.uri = uri;
}
this.era = era;
this.sender = sender;
-
- String trunkName = this.storage.setupChunkFolder(era, targetUri);
+
+ //Log.writeLog(this, this.toString(), "construct chunkFS");
+ String trunkName = this.storage.setupChunkFolder(era, uri);
// init
this.initFiles(trunkName);
}
- ASAPChunkFS(ASAPChunkStorageFS storage, String trunkName) throws IOException {
+ public ASAPInternalChunkFS(ASAPChunkStorageFS storage, String trunkName) throws IOException {
this.storage = storage;
- this.uri = ASAPChunkFS.DEFAULT_URL;
+ this.uri = ASAPInternalChunkFS.DEFAULT_URL;
this.initFiles(trunkName);
}
@@ -88,22 +111,30 @@ public List getDeliveredTo() {
private void initFiles(String trunkName) throws IOException {
String messageFileName = trunkName + "." + DATA_EXTENSION;
String metaFileName = trunkName + "." + META_DATA_EXTENSION;
-
+
this.messageFile = new File(messageFileName);
this.metaFile = new File(metaFileName);
// init meta file - message file keeps untouched (good idea?)
if(!this.metaFile.exists()) {
+ Log.writeLog(this, "meta file does not exist / set up: " + this.metaFile);
+ if(!this.metaFile.getParentFile().exists()) {
+ this.metaFile.getParentFile().mkdirs();
+ //Log.writeLog(this, "parent folder created: " + this.messageFile.getParentFile().exists());
+ }
this.metaFile.createNewFile();
+ } else {
+ Log.writeLog(this, "meta file does already exists: " + this.metaFile);
}
// try to read existing meta data
if(!this.readMetaData(this.metaFile)) {
- // no metadate to be read - set defaults
+ // no meta date to be read - set defaults
this.writeMetaData(this.metaFile);
this.recipients = new HashSet<>();
this.deliveredTo = new ArrayList<>();
this.messageStartOffsets = new ArrayList<>();
+ this.hopList = new ArrayList<>();
}
}
@@ -125,8 +156,10 @@ public void addRecipient(CharSequence recipient) throws IOException {
@Override
public void setRecipients(Collection newRecipients) throws IOException {
this.recipients = new HashSet<>();
- for(CharSequence recipient : newRecipients) {
- this.recipients.add(recipient);
+ if(recipients != null) {
+ for (CharSequence recipient : newRecipients) {
+ this.recipients.add(recipient);
+ }
}
this.writeMetaData(this.metaFile);
@@ -143,11 +176,12 @@ public String getUri() {
return (String) this.uri;
}
+ /*
@Override
public void addMessage(CharSequence message) throws IOException {
this.addMessage(message.toString().getBytes());
}
-
+*/
@Override
public void addMessage(byte[] messageAsBytes) throws IOException {
if(messageAsBytes.length > Integer.MAX_VALUE) {
@@ -160,18 +194,32 @@ public void addMessage(byte[] messageAsBytes) throws IOException {
}
public void addMessage(InputStream messageByteIS, long length) throws IOException {
+ //Log.writeLog(this, "going to add message to chunkFS" );
if(length > Integer.MAX_VALUE) {
throw new IOException("message must not be longer than Integer.MAXVALUE");
}
- long offset = this.messageFile.length();
+ long offset = 0;
+ if(!this.messageFile.exists()) {
+ if(!this.messageFile.getParentFile().exists()) {
+ this.messageFile.getParentFile().mkdirs();
+ Log.writeLog(this, "parent folder created: " + this.messageFile.getParentFile().exists());
+ }
+ this.messageFile.createNewFile();
+ } else {
+ offset = this.messageFile.length();
+ }
+ //Log.writeLog(this, "got chunk content file length: " + offset);
OutputStream os = new FileOutputStream(this.messageFile, true);
+ //Log.writeLog(this, "opened chunk content file to append data");
+ //Log.writeLog(this, "write message to the end of chunk file");
while(length-- > 0) {
os.write(messageByteIS.read());
}
+ //Log.writeLog(this, "closing");
os.close();
// remember offset if not 0
@@ -182,7 +230,7 @@ public void addMessage(InputStream messageByteIS, long length) throws IOExceptio
}
@Override
- public Iterator getMessagesAsBytes() throws IOException {
+ public Iterator getMessages() throws IOException {
return this.getMessagesAsBytesList().iterator();
}
@@ -269,7 +317,7 @@ public CharSequence getExtra(String key) throws IOException {
}
@Override
- public Iterator getMessages() throws IOException {
+ public Iterator getMessagesAsCharSequence() throws IOException {
try {
return new MessageIter(this.getMessagesAsBytesList());
} catch (FileNotFoundException ex) {
@@ -289,45 +337,111 @@ private boolean readMetaData(File metaFile) throws IOException {
DataInputStream dis = new DataInputStream(new FileInputStream(metaFile));
try {
+ // do it as first element - shure how many bytes we read..
+ this.hopList = ASAPSerialization.readASAPHopList(dis);
+
this.uri = dis.readUTF();
this.setExtraByString(dis.readUTF());
}
- catch(EOFException eof) {
+ catch(EOFException | ASAPException eof) {
// file empty
return false;
}
try {
- this.recipients = Helper.string2CharSequenceSet(dis.readUTF());
- this.deliveredTo = Helper.string2CharSequenceList(dis.readUTF());
+ this.recipients = SerializationHelper.string2CharSequenceSet(dis.readUTF());
+ this.deliveredTo = SerializationHelper.string2CharSequenceList(dis.readUTF());
// finally read offset list
String offsetList = dis.readUTF();
this.messageStartOffsets = this.messageOffsetString2List(offsetList);
}
- catch(IOException ioe) {
+ catch(IOException e) {
// no more data - ok
- }
- finally {
+ } finally {
dis.close();
}
return true;
}
- private void writeMetaData(File metaFile) throws IOException {
+ private void writeMetaData(File file2writeMetaData) throws IOException {
// write data to metafile
- DataOutputStream dos = new DataOutputStream(new FileOutputStream(metaFile));
-
- dos.writeUTF(this.uri);
- dos.writeUTF(this.getExtraAsString());
- dos.writeUTF(Helper.collection2String(this.recipients));
- dos.writeUTF(Helper.collection2String(this.deliveredTo));
+ /*
+ if(file2writeMetaData.exists()) {
+ if(file2writeMetaData.getAbsolutePath().contains("ultihopTests/Alice_42/1/sha")) {
+ Log.writeLog(this, this.toString(), "\nDEBUGGING_Multihop_Bug #1: " +
+ "\nfile2WriteMetaData:" + file2writeMetaData.getAbsolutePath() +
+ "\nexists:" + file2writeMetaData.exists() +
+ "\ncanWrite:" + file2writeMetaData.canWrite()
+ );
+ }
+ this.metaFile.delete();
+ this.metaFile.createNewFile();
+ }
+ */
- // write offsetList
- dos.writeUTF(this.messageStartOffsetListAsString());
-
- dos.close();
+ try {
+ /*
+ if(file2writeMetaData.getAbsolutePath().contains("ultihopTests/Alice_42/1/sha")) {
+ Log.writeLog(this, this.toString(), "\nDEBUGGING_Multihop_Bug #1: open:" +
+ "\nfile2WriteMetaData:" + file2writeMetaData.getAbsolutePath() +
+ "\nexists:" + file2writeMetaData.exists() +
+ "\ncanWrite:" + file2writeMetaData.canWrite()
+ );
+ }
+ */
+ FileOutputStream fos = new FileOutputStream(file2writeMetaData);
+ Log.writeLog(this, this.toString(), "\\nDEBUGGING_Multihop_Bug: write meta data to:" +
+ "\nfile2WriteMetaData:" + file2writeMetaData.getAbsolutePath() +
+ "\nexists:" + file2writeMetaData.exists() +
+ "\ncanWrite:" + file2writeMetaData.canWrite()
+ );
+ DataOutputStream dos = new DataOutputStream(fos);
+
+ // do it as first element - shure how many bytes we read..
+ ASAPSerialization.writeASAPHopList(this.hopList, dos);
+
+ dos.writeUTF(this.uri);
+ dos.writeUTF(this.getExtraAsString());
+ dos.writeUTF(SerializationHelper.collection2String(this.recipients));
+ dos.writeUTF(SerializationHelper.collection2String(this.deliveredTo));
+
+ // write offsetList
+ dos.writeUTF(this.messageStartOffsetListAsString());
+
+ fos.close();
+ dos.close();
+ }
+ catch(IOException ioe) {
+ // TODO: debugging code
+ Log.writeLog(this, this.toString(), "\nDEBUGGING_Multihop_Bug #3: file2WriteMetaData:" +
+ "\nfile2WriteMetaData:" + file2writeMetaData.getAbsolutePath() +
+ "\nexists:" + file2writeMetaData.exists() +
+ "\ncanWrite:" + file2writeMetaData.canWrite());
+ String fname = new StringTokenizer(ioe.getLocalizedMessage()).nextToken();
+ Log.writeLog(this, this.toString(), "\nDEBUGGING_Multihop_Bug #4: not found" +
+ "\nfile2WriteMetaData:" + file2writeMetaData.getAbsolutePath());
+ File fNotFound = new File(fname);
+ Log.writeLog(this, this.toString(), "\nDEBUGGING_Multihop_Bug #5: file not found" +
+ "\nfile2WriteMetaData:" + fNotFound.getAbsolutePath() +
+ "\nexists:" + fNotFound.exists() +
+ "\ncanWrite:" + fNotFound.canWrite());
+ System.out.flush();
+ try {
+ // debugging output
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ //throw new RuntimeException(e);
+ }
+ Log.writeLog(this, this.toString(), "DEBUGGING_Multihop_Bug - try write again");
+ FileOutputStream fos = new FileOutputStream(fNotFound);
+ fos.write(42);
+ // never reaches that point
+ Log.writeLog(this, this.toString(), "DEBUGGING_Multihop_Bug - wrote");
+
+ throw ioe;
+ }
}
private String messageStartOffsetListAsString() {
@@ -336,7 +450,7 @@ private String messageStartOffsetListAsString() {
boolean first = true;
for(Long offset : this.messageStartOffsets) {
if(!first) {
- sb.append(Helper.SERIALIZATION_DELIMITER);
+ sb.append(ASAPLogHelper.SERIALIZATION_DELIMITER);
}
first = false;
sb.append(offset.toString());
@@ -356,10 +470,10 @@ private String getExtraAsString() throws IOException {
};
if(first) { first = false; }
- else { sb.append(Helper.SERIALIZATION_DELIMITER); }
+ else { sb.append(ASAPLogHelper.SERIALIZATION_DELIMITER); }
sb.append(key);
- sb.append(Helper.SERIALIZATION_DELIMITER);
+ sb.append(ASAPLogHelper.SERIALIZATION_DELIMITER);
sb.append(value);
}
@@ -371,7 +485,7 @@ private void setExtraByString(String extraString) throws IOException {
try {
HashMap extra = new HashMap<>();
- StringTokenizer st = new StringTokenizer(extraString, Helper.SERIALIZATION_DELIMITER);
+ StringTokenizer st = new StringTokenizer(extraString, ASAPLogHelper.SERIALIZATION_DELIMITER);
while (st.hasMoreTokens()) {
String key = st.nextToken();
String value = st.nextToken();
@@ -392,7 +506,7 @@ private ArrayList messageOffsetString2List(String s) {
if(s == null || s.length() == 0) return longList;
- StringTokenizer t = new StringTokenizer(s, Helper.SERIALIZATION_DELIMITER);
+ StringTokenizer t = new StringTokenizer(s, ASAPLogHelper.SERIALIZATION_DELIMITER);
while(t.hasMoreTokens()) {
Long offsetLong = Long.parseLong(t.nextToken());
@@ -414,29 +528,7 @@ public int getEra() throws IOException {
return this.era;
}
- private class MessageIter implements Iterator {
- private final List byteMessages;
- private int nextIndex;
- private String nextString;
-
-
- MessageIter(List byteMessages) throws FileNotFoundException {
- this.byteMessages = byteMessages;
- this.nextIndex = 0;
- }
-
- @Override
- public boolean hasNext() {
- return this.byteMessages.size() > nextIndex;
- }
-
- @Override
- public String next() {
- if(!this.hasNext()) {
- throw new NoSuchElementException("no more messages");
- }
-
- return new String(this.byteMessages.get(nextIndex++));
- }
+ public String toString() {
+ return "sender: " + this.sender + " | era: " + era + " | metafile: " + this.metaFile;
}
}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPInternalOnlinePeersChangedListener.java b/src/main/java/net/sharksystem/asap/engine/ASAPInternalOnlinePeersChangedListener.java
new file mode 100644
index 0000000..a9058af
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPInternalOnlinePeersChangedListener.java
@@ -0,0 +1,5 @@
+package net.sharksystem.asap.engine;
+
+public interface ASAPInternalOnlinePeersChangedListener {
+ void notifyOnlinePeersChanged(ASAPInternalPeer engine);
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPInternalPeer.java b/src/main/java/net/sharksystem/asap/engine/ASAPInternalPeer.java
new file mode 100644
index 0000000..b68b03f
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPInternalPeer.java
@@ -0,0 +1,164 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.SharkException;
+import net.sharksystem.asap.ASAPConnectionHandler;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPSecurityException;
+import net.sharksystem.asap.protocol.*;
+import net.sharksystem.asap.crypto.ASAPKeyStore;
+import net.sharksystem.fs.ExtraData;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Set;
+
+/**
+ * There is an ASAPEngine that stores its data with a filesystem.
+ * One significant parameter is a root directory.
+ *
+ * It is good practice to use a different root for each application.
+ *
+ * It is also common that more than one ASAP based app is running
+ * on one machine. Thus, different ASAP filesystem based engine are
+ * to deal with the data depending on the ASAP format.
+ *
+ * That interface hides those different engines.
+ */
+public interface ASAPInternalPeer extends ASAPConnectionHandler, ExtraData {
+ long DEFAULT_MAX_PROCESSING_TIME = Long.MAX_VALUE;
+
+ /**
+ * get an existing engine
+ * @param format
+ * @return
+ * @throws ASAPException engine does not exist
+ * @throws IOException
+ */
+ ASAPEngine getEngineByFormat(CharSequence format) throws ASAPException, IOException;
+
+ boolean asapRoutingAllowed(CharSequence applicationFormat) throws IOException, ASAPException;
+
+ void setAsapRoutingAllowed(CharSequence applicationFormat, boolean allowed)
+ throws IOException, ASAPException;
+
+ /**
+ * return already existing or create an engine for a given format / application name
+ * @param format
+ * @return
+ * @throws ASAPException
+ * @throws IOException
+ */
+ ASAPEngine createEngineByFormat(CharSequence format) throws ASAPException, IOException;
+
+ ASAPChunkAssimilatedListener getListenerByFormat(CharSequence format) throws ASAPException;
+
+ /**
+ * get or create engine for a given application - mainly means: setup folder
+ * @param format
+ * @return
+ */
+ ASAPEngine getASAPEngine(CharSequence format) throws IOException, ASAPException;
+
+ void pushInterests(OutputStream os) throws IOException, ASAPException;
+
+ Set getOnlinePeers();
+
+ boolean existASAPConnection(CharSequence recipient);
+
+ ASAPConnection getASAPConnection(CharSequence recipient);
+
+ CharSequence getOwner();
+
+ void newEra() throws IOException, ASAPException;
+
+ void setASAPChunkReceivedListener(CharSequence appName, ASAPChunkAssimilatedListener listener) throws ASAPException;
+
+ void addOnlinePeersChangedListener(ASAPInternalOnlinePeersChangedListener listener);
+
+ void removeOnlinePeersChangedListener(ASAPInternalOnlinePeersChangedListener listener);
+
+ /**
+ * @return true if the asap management engine is up and running
+ */
+ boolean isASAPManagementEngineRunning();
+
+ EngineSetting getEngineSettings(CharSequence format) throws ASAPException;
+
+ /**
+ * @return all formats currently supported by this mulit engine
+ */
+ Set getFormats();
+
+ void activateOnlineMessages();
+ void deactivateOnlineMessages();
+
+ /**
+ * A transient message is not stored and not meant to be forwarded. Sending a transient message has no effect
+ * without a running encounter. Despite that, it is an ordinary ASAP message - described by an application/format
+ * and an optional uri.
+ *
+ * @param nextHopPeerIDs A peer can have multiple encounter at the same time. This list - if present, names
+* potential message receiver. If null, message is sent to any open connection. An exception
+ * is not thrown if there is no connection to one or more peers in the list
+ * @param format message application / format
+ * @param urlTarget describe message within your app
+ * @param messageAsBytes serialized message
+ * @throws IOException
+ * @throws ASAPException
+ */
+ void sendTransientASAPAssimilateMessage(CharSequence format, CharSequence urlTarget,
+ Set nextHopPeerIDs, byte[] messageAsBytes) throws IOException, ASAPException;
+
+ /**
+ * Send a transient message to a single peer.
+ * An exception is thrown if there is no open connection the the specified peer
+ * @param format
+ * @param urlTarget
+ * @param nextHopPeerID
+ * @param messageAsBytes
+ * @throws IOException
+ * @throws ASAPException
+ */
+ void sendTransientASAPAssimilateMessage(CharSequence format, CharSequence urlTarget,
+ CharSequence nextHopPeerID, byte[] messageAsBytes) throws IOException, ASAPException;
+
+ /**
+ * Send a transient message to any peer we have an open connection to.
+ *
+ * @param format
+ * @param urlTarget
+ * @param messageAsBytes
+ * @throws IOException
+ * @throws ASAPException
+ */
+ void sendTransientASAPAssimilateMessage(CharSequence format, CharSequence urlTarget, byte[] messageAsBytes)
+ throws IOException, ASAPException;
+
+ /**
+ * @deprecated use sendTransientASAPAssimilateMessage instead
+ * @param format
+ * @param urlTarget
+ * @param era
+ * @param recipients
+ * @param messageAsBytes
+ * @throws IOException
+ * @throws ASAPException
+ */
+ void sendOnlineASAPAssimilateMessage(CharSequence format, CharSequence urlTarget, int era,
+ Set recipients, byte[] messageAsBytes) throws IOException, ASAPException;
+
+ void sendOnlineASAPAssimilateMessage(CharSequence format, CharSequence urlTarget, int era, byte[] messageAsBytes)
+ throws IOException, ASAPException;
+
+ void setASAPKeyStore(ASAPKeyStore ASAPKeyStore);
+ ASAPKeyStore getASAPKeyStore();
+
+ ASAPCommunicationSetting getASAPCommunicationControl();
+
+ ASAPKeyStore getAsapKeyStore() throws ASAPSecurityException;
+
+ ExtraData getExtraData() throws SharkException, IOException;
+
+ void setSecurityAdministrator(DefaultSecurityAdministrator securityAdministrator);
+
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPInternalPeerFS.java b/src/main/java/net/sharksystem/asap/engine/ASAPInternalPeerFS.java
new file mode 100644
index 0000000..e191caf
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPInternalPeerFS.java
@@ -0,0 +1,757 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.SharkException;
+import net.sharksystem.asap.ASAPEncounterConnectionType;
+import net.sharksystem.asap.crypto.*;
+import net.sharksystem.fs.ExtraData;
+import net.sharksystem.fs.ExtraDataFS;
+import net.sharksystem.utils.*;
+import net.sharksystem.asap.ASAP;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPSecurityException;
+import net.sharksystem.asap.listenermanager.management.ASAPManagementMessageHandler;
+import net.sharksystem.asap.protocol.*;
+
+import java.io.*;
+import java.util.*;
+
+public class ASAPInternalPeerFS implements
+ ASAPInternalPeer, ASAPConnectionListener, ThreadFinishedListener, ASAPUndecryptableMessageHandler/*, ASAPChunkReceivedListener */ {
+
+ private static final String DEFAULT_ASAP_MANAGEMENT_ENGINE_ROOTFOLDER = "ASAPManagement";
+ private final CharSequence rootFolderName;
+ private final ASAPChunkAssimilatedListener listener;
+ private CharSequence owner;
+ private HashMap folderMap;
+ private final long maxExecutionTime;
+ private ASAPKeyStore asapKeyStore;
+ private DefaultSecurityAdministrator defaultSecurityAdministrator = new DefaultSecurityAdministrator();
+ private InMemoASAPKeyStore inMemoASAPKeyStore;
+
+ public ASAPPoint2PointCryptoSettings getASAPCommunicationCryptoSettings() {
+ return this.defaultSecurityAdministrator;
+ }
+
+ public void setSecurityAdministrator(DefaultSecurityAdministrator securityAdministrator) {
+ this.defaultSecurityAdministrator = securityAdministrator;
+ }
+
+ public ASAPCommunicationSetting getASAPCommunicationControl() {
+ return this.defaultSecurityAdministrator;
+ }
+
+ public static ASAPInternalPeer createASAPPeer(CharSequence owner, CharSequence rootFolder,
+ long maxExecutionTime,
+ Collection supportFormats,
+ ASAPChunkAssimilatedListener listener)
+ throws ASAPException, IOException {
+
+ return new ASAPInternalPeerFS(owner, rootFolder, maxExecutionTime, supportFormats, listener);
+ }
+
+ public static ASAPInternalPeer createASAPPeer(CharSequence owner, CharSequence rootFolder,
+ Collection supportFormats,
+ ASAPChunkAssimilatedListener listener)
+ throws ASAPException, IOException {
+
+ return new ASAPInternalPeerFS(owner, rootFolder, DEFAULT_MAX_PROCESSING_TIME, supportFormats, listener);
+ }
+
+ public static ASAPInternalPeer createASAPPeer(CharSequence owner, CharSequence rootFolder,
+ long maxExecutionTime,
+ ASAPChunkAssimilatedListener listener) throws ASAPException, IOException {
+ return new ASAPInternalPeerFS(owner, rootFolder, maxExecutionTime, listener);
+ }
+
+ public static ASAPInternalPeer createASAPPeer(CharSequence owner, CharSequence rootFolder,
+ ASAPChunkAssimilatedListener listener) throws ASAPException, IOException {
+ return new ASAPInternalPeerFS(owner, rootFolder, DEFAULT_MAX_PROCESSING_TIME, listener);
+ }
+
+ public static ASAPInternalPeer createASAPPeer(CharSequence folder, ASAPChunkAssimilatedListener listener)
+ throws ASAPException, IOException {
+
+ return ASAPInternalPeerFS.createASAPPeer(ASAPEngine.DEFAULT_OWNER, folder,
+ DEFAULT_MAX_PROCESSING_TIME, listener);
+ }
+
+ /**
+ * assumed that a number of asap storages are already exists in subdirectories of the
+ * root directory. setting list can be created by iterating those storages.
+ * @param rootFolderName
+ */
+ private ASAPInternalPeerFS(CharSequence owner, CharSequence rootFolderName, long maxExecutionTime,
+ ASAPChunkAssimilatedListener listener) throws ASAPException, IOException {
+ this(owner, rootFolderName, maxExecutionTime, null, listener);
+ }
+
+ private ASAPInternalPeerFS(CharSequence owner, CharSequence rootFolderName, long maxExecutionTime,
+ Collection apps, ASAPChunkAssimilatedListener listener)
+ throws ASAPException, IOException {
+
+ // owner id must not be a numerical value only - it would interfere with our era numbers
+ try {
+ Integer.parseInt(owner.toString());
+ throw new ASAPException("peer id must not only be a numeric number like 42. " +
+ "It can be ArthurDent_42, though: " + owner);
+ }
+ catch(NumberFormatException e) {
+ // that's a good thing - id is not only a number
+ }
+
+ this.owner = owner;
+ this.maxExecutionTime = maxExecutionTime;
+ this.rootFolderName = rootFolderName;
+ this.listener = listener;
+
+ File rootFolder = new File(rootFolderName.toString());
+
+ if(!rootFolder.exists()) {
+ // create
+ rootFolder.mkdirs();
+ }
+
+ if (!rootFolder.isDirectory()) {
+ throw new ASAPException("exists but is not a directory: " + rootFolderName);
+ }
+
+ this.setupFolderMap();
+
+ /////////////////// asap management app //////////////////////////////////////////////////////
+ // check if management engine running
+ /*
+ if(!this.isASAPManagementEngineRunning()) {
+ Log.writeLog(this, "no asap management engine yet - set it up.");
+
+ this.setupEngine(DEFAULT_ASAP_MANAGEMENT_ENGINE_ROOTFOLDER, ASAP_1_0.ASAP_MANAGEMENT_FORMAT);
+ }
+ */
+
+ // set listener to asap management app
+ EngineSetting folderAndListener = folderMap.get(ASAP_1_0.ASAP_MANAGEMENT_FORMAT);
+ if(folderAndListener != null) {
+ folderAndListener.listener = new ASAPManagementMessageHandler(this);
+ }
+
+ /////////////////// not yet created engines////////////////////////////////////////////////////
+ if(apps != null) {
+ for (CharSequence appFormat : apps) {
+ // check if exists
+ try {
+ this.getEngineByFormat(appFormat);
+ } catch (ASAPException e) {
+ // set it up
+ this.setupEngine(Utils.url2FileName(appFormat.toString()), appFormat);
+ }
+ }
+ }
+
+ //this.restoreExtraData();
+
+// Log.writeLog(this, "SHOULD also set up engine " + FORMAT_UNDECRYPTABLE_MESSAGES);
+ }
+
+ private void setupEngine(CharSequence folderName, CharSequence formatName) throws IOException, ASAPException {
+ String fileName = this.rootFolderName + "/" + folderName;
+ Log.writeLog(this, "set up: " + formatName + " in folder " + fileName);
+ ASAPEngine asapEngine = ASAPEngineFS.getASAPStorage(this.getOwner().toString(),
+ fileName, formatName);
+
+ asapEngine.setSecurityAdministrator(this.defaultSecurityAdministrator);
+
+ EngineSetting setting = new EngineSetting(
+ fileName, // folder
+ this.listener// listener
+ );
+ setting.setASAPEngine(asapEngine);
+ this.folderMap.put(formatName, setting);
+ }
+
+ private void setupFolderMap() throws IOException, ASAPException {
+ this.folderMap = new HashMap<>();
+ File rootFolder = new File(rootFolderName.toString());
+
+ Log.writeLog(this, "setting up ASAPEngine based on sub folders in " + this.rootFolderName);
+ File[] files = rootFolder.listFiles();
+ for (File file : files) {
+ if (file.isDirectory()) {
+ String fileName = file.getCanonicalPath();
+ Log.writeLog(this, "setup engine for " + fileName);
+ ASAPEngine engine = ASAPEngineFS.getExistingASAPEngineFS(fileName);
+ EngineSetting setting = new EngineSetting(
+ rootFolderName + "/" + fileName, // folder
+ listener// listener
+ );
+ setting.setASAPEngine(engine);
+ this.folderMap.put(engine.format, setting);
+ }
+ }
+ }
+
+ /**
+ * increase era for each engine
+ */
+ public void newEra() throws IOException, ASAPException {
+ for(CharSequence format : this.folderMap.keySet()) {
+ ASAPEngine engine = this.getEngineByFormat(format);
+ engine.newEra();
+ }
+ }
+
+ @Override
+ public void setASAPChunkReceivedListener(CharSequence appName, ASAPChunkAssimilatedListener listener)
+ throws ASAPException {
+
+ EngineSetting engineSetting = this.folderMap.get(appName);
+ if(engineSetting == null) {
+ throw new ASAPException("there is no ASAPEngine for app/format " + appName);
+ }
+
+ engineSetting.listener = listener;
+ }
+
+ public CharSequence getOwner() {
+ return this.owner;
+ }
+
+ public ASAPEngine getEngineByFormat(CharSequence format) throws ASAPException, IOException {
+ // get engine
+ EngineSetting engineSetting = this.getEngineSettings(format);
+ ASAPEngine asapEngine = engineSetting.engine;
+
+ if (asapEngine == null) {
+ asapEngine = ASAPEngineFS.getASAPEngine(owner.toString(), engineSetting.folder.toString(), format);
+ engineSetting.setASAPEngine(asapEngine); // remember - keep that object
+ }
+ asapEngine.setSecurityAdministrator(this.defaultSecurityAdministrator);
+ return asapEngine;
+ }
+
+ public boolean asapRoutingAllowed(CharSequence applicationFormat) throws IOException, ASAPException {
+ return this.getEngineByFormat(applicationFormat).routingAllowed();
+ }
+
+ public void setAsapRoutingAllowed(CharSequence applicationFormat, boolean allowed)
+ throws IOException, ASAPException {
+
+ this.getEngineByFormat(applicationFormat).setBehaviourAllowRouting(allowed);
+ }
+
+ @Override
+ public ASAPEngine createEngineByFormat(CharSequence format) throws ASAPException, IOException {
+ try {
+ return this.getEngineByFormat(format);
+ }
+ catch(ASAPException e) {
+ // does not exist yet
+ }
+
+ String folderName = this.getEngineFolderByAppName(format);
+ ASAPEngine asapEngine = ASAPEngineFS.getASAPEngine(String.valueOf(this.getOwner()), folderName, format);
+ this.folderMap.put(format, new EngineSetting(folderName, listener));
+
+ asapEngine.setSecurityAdministrator(this.defaultSecurityAdministrator);
+
+ return asapEngine;
+ }
+
+ @Override
+ public ASAPChunkAssimilatedListener getListenerByFormat(CharSequence format) throws ASAPException {
+ EngineSetting engineSetting = this.folderMap.get(format);
+ if(engineSetting == null) throw new ASAPException("unknown format: " + format);
+
+ return engineSetting.listener;
+ }
+
+ private String getEngineFolderByAppName(CharSequence appName) {
+ return this.rootFolderName.toString() + "/" + Utils.url2FileName(appName.toString());
+ }
+
+ @Override
+ public ASAPEngine getASAPEngine(CharSequence format)
+ throws IOException, ASAPException {
+
+ String foldername = this.getEngineFolderByAppName(format);
+ // already exists?
+ try {
+ ASAPEngine existingASAPEngineFS = ASAPEngineFS.getExistingASAPEngineFS(foldername);
+ if(existingASAPEngineFS != null) {
+ return existingASAPEngineFS;
+ }
+ }
+ catch(ASAPException e) {
+ Log.writeLog(this, "engine does not yet exist. folder " + foldername);
+ }
+
+ Log.writeLog(this, "setup engine with folder" + foldername);
+ ASAPEngine asapEngine = ASAPEngineFS.getASAPEngine(this.getOwner().toString(), foldername, format);
+ // add to folderMap
+ EngineSetting setting = new EngineSetting(foldername, this.listener);
+ setting.setASAPEngine(asapEngine);
+ this.folderMap.put(format, setting);
+
+ return asapEngine;
+ }
+
+ public EngineSetting getEngineSettings(CharSequence format) throws ASAPException {
+ EngineSetting folderAndListener = this.folderMap.get(format);
+ if(folderAndListener == null)
+ throw new ASAPException("no folder for owner / format: " + owner + "/" + format);
+
+ return folderAndListener;
+ }
+
+ public Set getFormats() {
+ return this.folderMap.keySet();
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // connection management //
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ public ASAPConnection handleConnection(InputStream is, OutputStream os) throws IOException, ASAPException {
+ return this.handleConnection(is, os, false, false);
+ }
+
+ public ASAPConnection handleConnection(InputStream is, OutputStream os,
+ boolean encrypt, boolean sign) throws IOException, ASAPException {
+
+ return this.handleConnection(is, os,false, false,null, null);
+ }
+
+ public ASAPConnection handleConnection(InputStream is, OutputStream os, ASAPEncounterConnectionType connectionType)
+ throws IOException, ASAPException {
+
+ return this.handleConnection(is, os,false, false, connectionType, null, null);
+ }
+
+ /**
+ *
+ * @deprecated need connection type
+ */
+ public ASAPConnection handleConnection(
+ InputStream is, OutputStream os, boolean encrypt, boolean sign,
+ Set appsWhiteList, Set appsBlackList
+ ) throws IOException, ASAPException {
+
+ return this.handleConnection(is, os, encrypt, sign,
+ ASAPEncounterConnectionType.UNKNOWN, appsWhiteList, appsBlackList);
+ }
+
+ public ASAPConnection handleConnection(
+ InputStream is, OutputStream os, boolean encrypt, boolean sign, ASAPEncounterConnectionType connectionType,
+ Set appsWhiteList, Set appsBlackList) throws IOException, ASAPException {
+
+ if(appsWhiteList == null) appsWhiteList = new HashSet<>(); // empty set no null
+ if(appsBlackList == null) appsBlackList = new HashSet<>(); // empty set no null
+
+ // TODO add white / black list.
+ ASAPSessionImpl asapConnection = new ASAPSessionImpl(
+ is, os, this, new ASAP_Modem_Impl(),
+ this, this.asapKeyStore,
+ maxExecutionTime, this, this, encrypt, sign, connectionType);
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(this.getLogStart());
+ sb.append("handleConnection");
+ Log.writeLog(this, sb.toString());
+
+ this.announceNewEra(); // announce when connection is actually established
+
+ Thread thread = new Thread(asapConnection);
+ thread.start();
+
+ // remember
+ this.runningThreads.add(thread);
+
+ sb = new StringBuilder();
+ sb.append(this.getLogStart());
+ sb.append("launched new asapConnection thread, total number is now: ");
+ sb.append(this.runningThreads.size());
+ Log.writeLog(this, sb.toString());
+
+ return asapConnection;
+ }
+
+ public void announceNewEra() throws IOException, ASAPException {
+ Log.writeLog(this, "announce new era");
+ for(CharSequence format : this.folderMap.keySet()) {
+ ASAPInternalStorage asapStorage = this.getEngineByFormat(format);
+ asapStorage.newEra();
+ }
+ }
+
+ /** all running threads */
+ private List runningThreads = new ArrayList<>();
+
+ @Override
+ public void finished(Thread thread) {
+ if(thread == null) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(this.getLogStart());
+ sb.append("finished thread cannot be null - do nothing");
+ Log.writeLogErr(this, sb.toString());
+ return;
+ }
+
+ this.runningThreads.remove(thread);
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(this.getLogStart());
+ sb.append("thread terminated - number of running threads is now: ");
+ sb.append(this.runningThreads.size());
+ Log.writeLog(this, sb.toString());
+ }
+
+ // threads connected to a peer
+ private Map connectedThreads = new HashMap<>();
+ private Map threadPeerNames = new HashMap<>();
+
+ private List onlinePeersChangedListeners = new ArrayList<>();
+ public void addOnlinePeersChangedListener(ASAPInternalOnlinePeersChangedListener listener) {
+ this.onlinePeersChangedListeners.add(listener);
+ }
+
+ public void removeOnlinePeersChangedListener(ASAPInternalOnlinePeersChangedListener listener) {
+ this.onlinePeersChangedListeners.remove(listener);
+ }
+
+ @Override
+ public boolean isASAPManagementEngineRunning() {
+ try {
+ ASAPEngine engineByFormat = this.getEngineByFormat(ASAP_1_0.ASAP_MANAGEMENT_FORMAT);
+ if(engineByFormat == null) {
+ return false;
+ }
+ } catch (ASAPException | IOException e) {
+ return false;
+ }
+
+ return true;
+ }
+
+ private void notifyOnlinePeersChangedListener() {
+ if(!this.connectedThreads.isEmpty()) {
+ Log.writeLog(this,
+ "#online peers: " + this.connectedThreads.keySet().size()
+ + " | " + SerializationHelper.collection2String(this.connectedThreads.keySet()));
+ } else {
+ Log.writeLog(this, "no (more) peers: ");
+ }
+
+ if(this.onlinePeersChangedListeners != null && !this.onlinePeersChangedListeners.isEmpty()) {
+ for(ASAPInternalOnlinePeersChangedListener listener: this.onlinePeersChangedListeners) {
+ listener.notifyOnlinePeersChanged(this);
+ }
+ } else {
+ Log.writeLog(this, "online peer changed but no listener");
+ }
+ }
+
+ public Set getOnlinePeers() {
+ if(!this.connectedThreads.isEmpty()) {
+ Log.writeLog(this,
+ "getOnlinePeers called | #online peers: " + this.connectedThreads.keySet().size()
+ + " | " + SerializationHelper.collection2String(this.connectedThreads.keySet()));
+ } else {
+ Log.writeLog(this, "getOnlinePeers called | no (more) peers: ");
+ }
+
+ return this.connectedThreads.keySet();
+ }
+
+ @Override
+ public void asapConnectionStarted(String remotePeerName, ASAPConnection asapConnection) {
+ if(asapConnection == null) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(this.getLogStart());
+ sb.append("asap connection started but asapConnection terminated cannot be null - do nothing");
+ Log.writeLogErr(this,sb.toString());
+ return;
+ }
+
+ /* we must do it handleConnection - this method is called when we are about processing the first interest pdu
+ try {
+ this.announceNewEra();
+ } catch (IOException | ASAPException e) {
+ Log.writeLogErr(this, "could not announce new era: " + e.getLocalizedMessage());
+ }
+ */
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(this.getLogStart());
+ sb.append("asap connection started, got a peername: ");
+ sb.append(remotePeerName);
+ Log.writeLog(this, sb.toString());
+
+ this.connectedThreads.put(remotePeerName, asapConnection);
+ this.threadPeerNames.put(asapConnection, remotePeerName);
+ this.notifyOnlinePeersChangedListener();
+ }
+
+ @Override
+ public synchronized void asapConnectionTerminated(Exception terminatingException, ASAPConnection asapConnection) {
+ if(asapConnection == null) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(this.getLogStart());
+ sb.append("terminated connection cannot be null - do nothing");
+ Log.writeLogErr(this, sb.toString());
+ return;
+ }
+
+ // get asapConnection name
+ CharSequence peerName = this.threadPeerNames.remove(asapConnection);
+ this.connectedThreads.remove(peerName);
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(this.getLogStart());
+ sb.append("asapConnection terminated; was connected to: ");
+
+ if(peerName != null) {
+ sb.append(peerName);
+ } else {
+ sb.append("null");
+ }
+
+ Log.writeLog(this, sb.toString());
+
+ if(peerName != null) {
+ try {
+ this.announceNewEra();
+ } catch (IOException | ASAPException e) {
+ Log.writeLogErr(this,"error when announcing new era: " + e.getLocalizedMessage());
+ }
+
+ this.notifyOnlinePeersChangedListener();
+ } else {
+ Log.writeLog(this,
+ "asap connection terminated connected to nobody: don't change era / don't notify listeners");
+ }
+ }
+
+ @Override
+ public boolean existASAPConnection(CharSequence recipient) {
+ return this.getASAPConnection(recipient) != null;
+ }
+
+ @Override
+ public ASAPConnection getASAPConnection(CharSequence recipient) {
+ return this.connectedThreads.get(recipient);
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // ASAP management //
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ public void pushInterests(OutputStream os) throws IOException, ASAPException {
+ ASAP_1_0 protocol = new ASAP_Modem_Impl();
+/*
+ // in any case: issue an interest for management information first
+ Log.writeLog(this, "send interest on " + ASAP_1_0.ASAP_MANAGEMENT_FORMAT);
+ protocol.interest(this.owner, null, ASAP_1_0.ASAP_MANAGEMENT_FORMAT,null, -1, -1, os, false);
+*/
+ if(this.folderMap.size() > 0) {
+ Log.writeLog(this, "start sending interest for apps/formats");
+ } else {
+ Log.writeLog(this, "no more apps/formats on that engine - no interests to be sent");
+ }
+
+ // management messages must be sent first - if any
+ try {
+ // exists?
+ ASAPEngine managementEngine = this.getEngineByFormat(ASAP_1_0.ASAP_MANAGEMENT_FORMAT);
+ Log.writeLog(this, "send interest for app/format: " + ASAP_1_0.ASAP_MANAGEMENT_FORMAT);
+ protocol.interest(this.owner, null,
+ ASAP_1_0.ASAP_MANAGEMENT_FORMAT,
+ null, ASAP_1_0.ERA_NOT_DEFINED, ASAP_1_0.ERA_NOT_DEFINED,
+ os,
+ this.getASAPCommunicationCryptoSettings());
+ }
+ catch(Exception e) {
+ // ignore - engine does not exist
+ }
+ // issue an interest for each owner / format combination
+ for(CharSequence format : this.folderMap.keySet()) {
+ if(format.toString().equalsIgnoreCase(ASAP_1_0.ASAP_MANAGEMENT_FORMAT)) continue; // already sent
+ ASAPEngine engine = this.getEngineByFormat(format);
+
+ engine.sendInterest(this.owner, protocol, os);
+ }
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // Online management //
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ @Override
+ public void activateOnlineMessages() {
+// ASAPOnlineMessageSender asapOnlineMessageSender = new ASAPOnlineMessageSenderEngineSide(this);
+
+ // iterate engines
+ for(ASAPEngine engine : this.getEngines()) {
+// engine.attachASAPMessageAddListener(asapOnlineMessageSender);
+ engine.activateOnlineMessages(this);
+ }
+ }
+
+ @Override
+ public void deactivateOnlineMessages() {
+ // iterate engines
+ for(ASAPEngine engine : this.getEngines()) {
+ engine.deactivateOnlineMessages();
+ }
+ }
+
+
+ @Override
+ public void setASAPKeyStore(ASAPKeyStore asapKeyStore) {
+ this.asapKeyStore = asapKeyStore;
+ }
+
+ public ASAPKeyStore getASAPKeyStore() {
+ return this.asapKeyStore;
+ }
+
+ public void sendTransientASAPAssimilateMessage(CharSequence format, CharSequence uri, byte[] messageAsBytes)
+ throws IOException, ASAPException {
+ this.sendTransientASAPAssimilateMessage(format, uri, (Set)null, messageAsBytes);
+ }
+
+ public void sendTransientASAPAssimilateMessage(CharSequence format, CharSequence uri,
+ Set nextHopPeerIDs, byte[] messageAsBytes) throws IOException, ASAPException {
+
+ this.sendOnlineASAPAssimilateMessage(format, uri, ASAP.TRANSIENT_ERA, nextHopPeerIDs, messageAsBytes);
+ }
+
+ public void sendTransientASAPAssimilateMessage(CharSequence format, CharSequence uri,
+ CharSequence nextHopPeerID, byte[] messageAsBytes) throws IOException, ASAPException {
+
+ if(nextHopPeerID == null) throw new ASAPException("next hop peer id must not be null");
+
+ if(!this.existASAPConnection(nextHopPeerID)) {
+ String log = "cannot send transient message. No open connection to peer with id: " + nextHopPeerID;
+ Log.writeLog(this, log);
+ throw new ASAPException(log);
+ }
+
+ Set nextHopPeerIDs = new HashSet<>();
+ nextHopPeerIDs.add(nextHopPeerID);
+ this.sendOnlineASAPAssimilateMessage(format, uri, ASAP.TRANSIENT_ERA, nextHopPeerIDs, messageAsBytes);
+ }
+
+ public void sendOnlineASAPAssimilateMessage(CharSequence format, CharSequence uri, int era, byte[] messageAsBytes)
+ throws IOException, ASAPException {
+
+ this.sendOnlineASAPAssimilateMessage(format, uri, era, null, messageAsBytes);
+ }
+
+ public void sendOnlineASAPAssimilateMessage(CharSequence format, CharSequence uri, int era,
+ Set receiver, byte[] messageAsBytes) throws IOException, ASAPException {
+ // setup online message sender thread
+ Log.writeLog(this, "setup online message sender object");
+ ASAPOnlineMessageSender asapOnlineMessageSender = new ASAPOnlineMessageSenderEngineSide(this);
+ Log.writeLog(this, "call send asap assimilate message with online message sender");
+ asapOnlineMessageSender.sendASAPAssimilateMessage(format, uri, receiver, messageAsBytes, ASAP.TRANSIENT_ERA);
+ }
+
+ private Collection getEngines() {
+ Collection engineList = new ArrayList<>();
+
+ if(this.folderMap.values() != null) {
+ for (EngineSetting engineSetting : this.folderMap.values()) {
+ engineList.add(engineSetting.engine);
+ }
+ }
+
+ return engineList;
+ }
+
+ private String getLogStart() {
+ return this.getClass().getSimpleName() /* + "(" + this + ")" */ + "(" + this.getOwner() + "): ";
+ }
+
+ //////////////////////////////// handle message this peer cannot decrypt
+ @Override
+ public void handleUndecryptableMessage(
+ ASAPCryptoAlgorithms.EncryptedMessagePackage encryptedMessagePackage,
+ CharSequence receiver) {
+
+ Log.writeLog(this, "handle undecryptable messages from " + receiver);
+
+ try {
+ ASAPEngine undecryptEngine =
+ this.getASAPEngine(ASAPUndecryptableMessageHandler.FORMAT_UNDECRYPTABLE_MESSAGES);
+
+ undecryptEngine.add(
+ URI_UNDECRYPTABLE_MESSAGES,
+ ASAPCryptoAlgorithms.getEncryptedMessagePackageAsBytes(encryptedMessagePackage));
+ } catch (IOException | ASAPException e) {
+ Log.writeLog(this, "cannot handle undecrypted messages - no engine present");
+ }
+ }
+
+ ///////////////////////////////// SharkNet
+ @Override
+ public ASAPKeyStore getAsapKeyStore() throws ASAPSecurityException {
+ if(this.inMemoASAPKeyStore == null) {
+ this.inMemoASAPKeyStore = new InMemoASAPKeyStore(this.getOwner().toString());
+ }
+ return this.inMemoASAPKeyStore;
+ }
+
+ ///////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // make extra data persist //
+ ///////////////////////////////////////////////////////////////////////////////////////////////////////////
+ private ExtraData extraData = null;
+
+ public ExtraData getExtraData() throws SharkException, IOException {
+ if(this.extraData == null) {
+ this.extraData = new ExtraDataFS(this.rootFolderName, "asapPeerExtraData");
+ }
+
+ return this.extraData;
+ }
+
+ public void putExtra(CharSequence key, byte[] value) throws IOException, SharkException {
+ this.getExtraData().putExtra(key, value);
+ }
+
+ @Override
+ public void putExtra(CharSequence key, Integer value) throws IOException, SharkException {
+ this.getExtraData().putExtra(key, value);
+ }
+
+ @Override
+ public void putExtra(CharSequence key, CharSequence value) throws IOException, SharkException {
+ this.getExtraData().putExtra(key, value);
+ }
+
+ @Override
+ public void putExtra(CharSequence key, Set value) throws IOException, SharkException {
+ this.getExtraData().putExtra(key, value);
+ }
+
+ public byte[] getExtra(CharSequence key) throws IOException, SharkException {
+ return this.getExtraData().getExtra(key);
+ }
+
+ @Override
+ public int getExtraInteger(CharSequence key) throws IOException, SharkException {
+ return this.getExtraData().getExtraInteger(key);
+ }
+
+ @Override
+ public Set getExtraCharSequenceSetParameter(CharSequence key) throws IOException, SharkException {
+ return this.getExtraData().getExtraCharSequenceSetParameter(key);
+ }
+
+ @Override
+ public String getExtraString(CharSequence key) throws IOException, SharkException {
+ return this.getExtraData().getExtraString(key);
+ }
+
+ @Override
+ public void removeAll() throws IOException, SharkException {
+ this.getExtraData().removeAll();
+ }
+}
diff --git a/src/net/sharksystem/asap/ASAPStorage.java b/src/main/java/net/sharksystem/asap/engine/ASAPInternalStorage.java
similarity index 51%
rename from src/net/sharksystem/asap/ASAPStorage.java
rename to src/main/java/net/sharksystem/asap/engine/ASAPInternalStorage.java
index 5bfe91a..307a68d 100644
--- a/src/net/sharksystem/asap/ASAPStorage.java
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPInternalStorage.java
@@ -1,16 +1,15 @@
-package net.sharksystem.asap;
+package net.sharksystem.asap.engine;
-import net.sharksystem.asap.apps.ASAPMessages;
-import net.sharksystem.asap.management.ASAPManagementStorage;
+import net.sharksystem.asap.*;
+import net.sharksystem.asap.listenermanager.management.ASAPManagementStorage;
import java.io.IOException;
import java.util.Collection;
-import java.util.List;
import java.util.Set;
/**
*
- * Communication break down in ad-hoc networks is normal and no failure.
+ * Break down of a communication channel in ad-hoc networks is normal and barely failure.
* That chunk storage is meant to keep messages which are produced by an
* app for later transmission.
*
@@ -18,7 +17,7 @@
* Each chunk is addressed with an URI (comparable to URIs e.g. in Android
* Content Provider)
*
- * Applications can easlily store their messages by calling add(URI, message).
+ * Applications can easily store their messages by calling add(URI, message).
* That message is stored in a chunk addressed by the URI.
*
* Each chunk has a recipient list which can be changed anytime. The ASAPEngine
@@ -33,7 +32,7 @@
* ASAPStorage myStorage = ASAPEngineFS.getASAPEngine("EngineName", "ChunkStorageRootFolder", reader);
*
*
- * An AASPReader must be implemented prior using that framework. Objects of
+ * An ASAPReader must be implemented prior using that framework. Objects of
* that class are called whenever another peer transmits messages to the
* local peer. @see AASPReader
*
@@ -43,20 +42,14 @@
* current era is declared to be finished and an new era is opened.
* Any new message is now tagged as message from that new era. The ASAPEngine
* transmits all message to the peer which are stored after the final
- * encounter. If no encounter ever happened - all availablee messages are
+ * encounter. If no encounter ever happened - all available messages are
* transmitted.
*
* @see ASAPEngine
*
* @author thsc
*/
-public interface ASAPStorage {
- /**
- * Get owner name (or id) of this storage
- * @return owner name (or id)
- */
- CharSequence getOwner();
-
+public interface ASAPInternalStorage extends ASAPStorage {
/**
* Creates a channel with named recipients - we call it a closed channel in opposite
* to an open channel.
@@ -70,7 +63,7 @@ public interface ASAPStorage {
void createChannel(CharSequence uri, Collection recipients) throws IOException, ASAPException;
/**
- * Create channel with a maybe different and than local peer - take care!
+ * Create channel (owner can differ from local peer owing this asap engine)
* @param owner
* @param uri
* @param recipients
@@ -79,21 +72,6 @@ public interface ASAPStorage {
*/
void createChannel(CharSequence owner, CharSequence uri, Collection recipients) throws IOException, ASAPException;
- /**
- *
- * @return list of channel uris present in this storage
- * @throws IOException
- */
- List getChannelURIs() throws IOException;
-
- /**
- *
- * @param uri
- * @return channel
- * @throws ASAPException if no channel with that uri exists in this storage
- */
- ASAPChannel getChannel(CharSequence uri) throws ASAPException, IOException;
-
/**
* Create a channel with only two members - creator and recipient
* @param urlTarget
@@ -102,14 +80,20 @@ public interface ASAPStorage {
*/
void createChannel(CharSequence urlTarget, CharSequence recipient) throws IOException, ASAPException;
- void removeChannel(CharSequence uri) throws IOException;
+ /**
+ * Create open channel
+ * @param urlTarget
+ * @throws IOException
+ * @throws ASAPException
+ */
+ void createChannel(CharSequence urlTarget) throws IOException, ASAPException;
/**
* Chunks are delivered when seeing other peers. This flag allows to decide whether delivered chunks
* are to be deleted.
* @param drop
*/
- void setDropDeliveredChunks(boolean drop) throws IOException;
+// void setDropDeliveredChunks(boolean drop) throws IOException;
/**
* Chunks are delivered when seeing other peers. Default behaviour is to send only message which
@@ -119,7 +103,7 @@ public interface ASAPStorage {
*
* @param drop
*/
- void setSendReceivedChunks(boolean drop) throws IOException;
+// void setSendReceivedChunks(boolean drop) throws IOException;
/**
/**
@@ -129,55 +113,22 @@ public interface ASAPStorage {
* @throws IOException
* @return
*/
- public Set getRecipients(CharSequence urlTarget) throws IOException;
+ Set getRecipients(CharSequence urlTarget) throws IOException;
- /**
- * Put some extra information on that channel
- * @param uri describing the channel
- * @param key
- * @param value
- * @throws IOException
- */
- public void putExtra(CharSequence uri, String key, String value) throws IOException;
-
- /**
- * Remove a string from extra information set
- * @param uri
- * @param key
- * @return
- * @throws IOException
- */
- public CharSequence removeExtra(CharSequence uri, String key) throws IOException;
+ void addRecipient(CharSequence urlTarget, CharSequence recipient) throws IOException;
+ void removeRecipient(CharSequence urlTarget, CharSequence recipient) throws IOException;
- /**
- * Get a string from extra information set without removing
- * @param uri
- * @param key
- * @return
- * @throws IOException
- */
- public CharSequence getExtra(CharSequence uri, String key) throws IOException;
-
- /**
- *
- * @param uri channel uri
- * @return if channel exists - in other words: at least one message was added with this channel uri
- */
- boolean channelExists(CharSequence uri) throws IOException;
-
/**
* Add a message to that chunk.
- * @param urlTarget chunk address
+ * @param uri message topic
* @param message Message to be kept for later transmission
* @throws IOException
*/
- void add(CharSequence urlTarget, CharSequence message) throws IOException;
-
- void add(CharSequence urlTarget, byte[] messageAsBytes) throws IOException;
+ void add(CharSequence uri, CharSequence message) throws IOException;
void attachASAPMessageAddListener(ASAPOnlineMessageSender asapOnlineMessageSender);
- void detachASAPMessageAddListener(ASAPOnlineMessageSender asapOnlineMessageSender);
+ void detachASAPMessageAddListener();
void setASAPManagementStorage(ASAPManagementStorage asapManagementStorage);
@@ -188,39 +139,6 @@ public interface ASAPStorage {
*/
public void newEra();
- /**
- * Get oldest era available on that peer.
- * @return
- */
- public int getOldestEra();
-
- /**
- * Get current era.
- * @return
- */
- public int getEra();
-
- /**
- * Get next era number. Era numbers are organized in a circle. Number 0
- * follows Integer.MAXVALUE. That method takes care of that fact.
- * No change is made on current era.
- *
- * @param era
- * @return
- */
- public int getNextEra(int era);
-
- /**
- * Get previous era number. Era numbers are organized in a circle. Er
- * number 0 is proceeded by era number Integer.MAXVALUE.
- * That method takes care of that fact.
- * No change is made on current era.
- *
- * @param era
- * @return
- */
- int getPreviousEra(int era);
-
/**
* Default behaviour of ASAPEngine: Each peer / communication partner
* gets its own chunk storage. That storage is filled during asap
@@ -229,26 +147,11 @@ public interface ASAPStorage {
* @param sender
* @return
*/
- ASAPChunkStorage getIncomingChunkStorage(CharSequence sender);
+ ASAPChunkStorage getReceivedChunksStorage(CharSequence sender);
- ASAPStorage getExistingIncomingStorage(CharSequence sender) throws IOException, ASAPException;
+ ASAPMessages getChunkChain(int uriPosition) throws IOException, ASAPException;
- /**
- *
- * @return list of peers with an incoming chunk storage
- */
- List getSender();
-
- /**
- *
- * @return The local chunk storage that is meant to be used by the local
- * app. Note: That storage is changed during an ASAP session.
- */
- ASAPChunkStorage getChunkStorage();
-
- ASAPMessages getChunkChain(int position) throws IOException, ASAPException;
-
- ASAPMessages getChunkChain(int position, int toEra) throws IOException, ASAPException;
+ ASAPMessages getChunkChain(int uriPosition, int toEra) throws IOException, ASAPException;
ASAPMessages getChunkChain(CharSequence uri, int toEra) throws IOException;
@@ -258,5 +161,12 @@ public interface ASAPStorage {
* Refresh with external system - re-read files, or whatever.
* @return refreshed object
*/
- ASAPStorage refresh() throws IOException, ASAPException;
+ ASAPInternalStorage refresh() throws IOException, ASAPException;
+
+ /**
+ * Get (and probably create a chunk - set era to this new era
+ * @param uri
+ * @param newEra
+ */
+ ASAPInternalChunk createNewChunk(String uri, int newEra) throws IOException;
}
diff --git a/src/net/sharksystem/asap/ASAPMemento.java b/src/main/java/net/sharksystem/asap/engine/ASAPMemento.java
similarity index 82%
rename from src/net/sharksystem/asap/ASAPMemento.java
rename to src/main/java/net/sharksystem/asap/engine/ASAPMemento.java
index a6ff60b..4cac349 100644
--- a/src/net/sharksystem/asap/ASAPMemento.java
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPMemento.java
@@ -1,4 +1,4 @@
-package net.sharksystem.asap;
+package net.sharksystem.asap.engine;
import java.io.IOException;
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPMementoFS.java b/src/main/java/net/sharksystem/asap/engine/ASAPMementoFS.java
new file mode 100644
index 0000000..27208c1
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPMementoFS.java
@@ -0,0 +1,209 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.protocol.ASAP_1_0;
+import net.sharksystem.utils.Log;
+
+import java.io.*;
+import java.util.HashMap;
+
+/**
+ * Engine memento implementation in filesystem.
+ *
+ * @author local
+ */
+class ASAPMementoFS implements ASAPMemento {
+ private final File rootDirectory;
+ private String owner;
+ private String format;
+ private int era;
+ private int oldestEra;
+ private boolean contentChanged;
+ private boolean dropDeliveredChunks;
+ private boolean sendReceivedChunks;
+ private HashMap lastSeen;
+ public long lastMementoWritten;
+
+ public ASAPMementoFS(File rootDirectory) {
+ this.rootDirectory = rootDirectory;
+ }
+
+ @Override
+ public void save(ASAPEngine engine) throws IOException {
+ /*
+ Log.writeLog(this, "\n" +
+ ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>save memento<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" +
+ ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>save memento<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
+ */
+ String fName = this.getMementoFileName();
+
+ File file = new File(fName);
+ if(!file.exists()) {
+ if(!file.createNewFile()) {
+ throw new IOException("could not create file (problems with directory?): " + fName);
+ }
+ }
+
+ DataOutputStream dos = new DataOutputStream(new FileOutputStream(fName));
+
+ long now = System.currentTimeMillis();
+
+ engine.lastMementoWritten = now;
+ this.lastMementoWritten = engine.lastMementoWritten;
+ dos.writeLong(now);
+ dos.writeUTF(engine.owner);
+ dos.writeUTF(engine.format);
+ dos.writeInt(engine.era);
+ dos.writeInt(engine.oldestEra);
+ dos.writeBoolean(engine.contentChanged);
+ this.contentChanged = engine.contentChanged;
+ dos.writeBoolean(engine.dropDeliveredChunks);
+ dos.writeBoolean(engine.routingAllowed);
+
+ // write lastSeen hash map
+ if(engine.lastSeen != null && !engine.lastSeen.isEmpty()) {
+ for(String key : engine.lastSeen.keySet()) {
+ Integer era = engine.lastSeen.get(key);
+
+ // write peer and era
+ dos.writeUTF(key);
+ dos.writeInt(era);
+ }
+ }
+
+ //Log.writeLog(this, "saved: " + this);
+ }
+
+ private void setDefaults(ASAPEngine engine) {
+ // set defaults
+ engine.owner = ASAPEngine.DEFAULT_OWNER;
+ engine.format = ASAP_1_0.ANY_FORMAT.toString();
+ engine.era = ASAPEngine.DEFAULT_INIT_ERA;
+ engine.oldestEra = ASAPEngine.DEFAULT_INIT_ERA;
+ engine.lastSeen = new HashMap<>();
+ engine.dropDeliveredChunks = false;
+ engine.routingAllowed = true;
+ }
+
+ public void read() throws IOException {
+ String fName = this.getMementoFileName();
+
+ File file = new File(fName);
+ if(!file.exists()) {
+ return;
+ }
+
+ DataInputStream dis = new DataInputStream(
+ new FileInputStream(file));
+
+ try {
+ this.lastMementoWritten = dis.readLong();
+ this.owner = dis.readUTF();
+ this.format = dis.readUTF();
+ this.era = dis.readInt();
+ this.oldestEra = dis.readInt();
+ this.contentChanged = dis.readBoolean();
+ this.dropDeliveredChunks = dis.readBoolean();
+ this.sendReceivedChunks = dis.readBoolean();
+ }
+ catch(EOFException e) {
+ // ignore and work with set defaults
+ return; // reached end of file - nothing to do here
+ }
+
+ // try to read lastSeen list
+ boolean first = true;
+ try {
+ for(;;) { // escapes from that loop via ioexception
+ String peer = dis.readUTF();
+ // got one
+ if(first) {
+ // init empty list
+ this.lastSeen = new HashMap<>();
+ first = false;
+ }
+
+ Integer era = dis.readInt();
+
+ // remember
+ this.lastSeen.put(peer, era);
+ }
+ }
+ catch(IOException ioe) {
+ // ok no more data
+ }
+ dis.close();
+ }
+
+ public void restore(ASAPEngine engine) throws IOException {
+ String fName = this.getMementoFileName();
+
+ File file = new File(fName);
+ if(!file.exists()) {
+ this.setDefaults(engine);
+ return;
+ }
+
+ DataInputStream dis = new DataInputStream(
+ new FileInputStream(file));
+
+ try {
+ engine.lastMementoWritten = dis.readLong();
+ this.lastMementoWritten = engine.lastMementoWritten;
+ engine.owner = dis.readUTF();
+ engine.format = dis.readUTF();
+ engine.era = dis.readInt();
+ engine.oldestEra = dis.readInt();
+ engine.contentChanged = dis.readBoolean();
+ this.contentChanged = engine.contentChanged;
+ engine.dropDeliveredChunks = dis.readBoolean();
+ engine.routingAllowed = dis.readBoolean();
+ }
+ catch(EOFException e) {
+ // ignore and work with set defaults
+ return; // reached end of file - nothing to do here
+ }
+
+ // try to read lastSeen list
+ boolean first = true;
+ try {
+ for(;;) { // escapes from that loop via ioexception
+ String peer = dis.readUTF();
+ // got one
+ if(first) {
+ // init empty list
+ engine.lastSeen = new HashMap<>();
+ first = false;
+ }
+
+ Integer era = dis.readInt();
+
+ // remember
+ engine.lastSeen.put(peer, era);
+ }
+ }
+ catch(IOException ioe) {
+ // ok no more data
+ }
+ dis.close();
+
+ //Log.writeLog(this, "restored: " + this);
+ }
+
+ private String getMementoFileName() {
+ return this.rootDirectory + "/" + ASAPEngineFS.MEMENTO_FILENAME;
+ }
+
+ public String getFormat() {
+ return this.format;
+ }
+
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("changed == ");
+ sb.append(this.contentChanged);
+ sb.append(" | written == ");
+ sb.append(this.lastMementoWritten);
+
+ return sb.toString();
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPMessagesMerger.java b/src/main/java/net/sharksystem/asap/engine/ASAPMessagesMerger.java
new file mode 100644
index 0000000..f37e0c3
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPMessagesMerger.java
@@ -0,0 +1,399 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.ASAPChunk;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPMessageCompare;
+import net.sharksystem.asap.ASAPMessages;
+import net.sharksystem.asap.utils.PeerIDHelper;
+
+import javax.xml.transform.Source;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+public class ASAPMessagesMerger implements ASAPMessages {
+ private final ASAPMessageCompare messageCompare;
+ private CharSequence format;
+ private CharSequence uri;
+ private int size;
+
+ private final ASAPMessages[] messageSources;
+ private List newFirstPositionList = new ArrayList<>();
+ private List oldFirstPositionList = new ArrayList<>();
+
+ private class SourceIndex {
+ public int wantedPosition; // overall position
+ public int sourceIndex; // which had fitting message
+ public int positionInSource; // position in source where to find message.
+
+ public SourceIndex(int wantedPosition, int sourceIndex, int positionInSource) {
+ this.wantedPosition = wantedPosition;
+ this.sourceIndex = sourceIndex;
+ this.positionInSource = positionInSource;
+ }
+ }
+
+ ASAPMessagesMerger(List messageSources, ASAPMessageCompare messageCompare)
+ throws ASAPException, IOException {
+ if(messageSources == null || messageSources.isEmpty())
+ throw new ASAPException("message source must not be null or empty");
+
+ this.messageCompare = messageCompare;
+ this.size = 0; // init;
+
+ // check integrity and find empty sources
+ this.format = null;
+ this.uri = null;
+ int notEmpty = 0;
+ for(ASAPMessages source : messageSources) {
+ CharSequence currentFormat = source.getFormat();
+ if(this.format != null && !PeerIDHelper.sameFormat(currentFormat, this.format)) {
+ throw new ASAPException("message source must not have different formats: " + this.format
+ + " != " + currentFormat);
+ }
+ // else
+ this.format = currentFormat;
+
+ CharSequence currentUri = source.getURI();
+ if(this.uri != null && !PeerIDHelper.sameFormat(currentUri, this.uri)) {
+ throw new ASAPException("message source must not have different uris: " + this.uri
+ + " != " + currentUri);
+ }
+
+ // else
+ this.uri = currentUri;
+ this.size += source.size();
+
+ if(source.size() > 0) notEmpty++;
+ }
+
+ // remember no empty sources
+ this.messageSources = new ASAPMessages[notEmpty];
+ int i = 0;
+ for(ASAPMessages source : messageSources) {
+ if(source.size() > 0) this.messageSources[i++] = source;
+ }
+
+ if(this.messageCompare == null) {
+ // source will be returned in their order
+ int globalIndex = 0;
+ for(int sIndex = 0; sIndex < this.messageSources.length; sIndex++) {
+ SourceIndex index = new SourceIndex(globalIndex, sIndex, 0);
+ this.oldFirstPositionList.add(index);
+ this.newFirstPositionList.add(index);
+ globalIndex += this.messageSources[sIndex].size();
+ }
+ // last entry
+ int lastSourceI = this.messageSources.length-1;
+ SourceIndex lastSourceIndex = new SourceIndex(
+ globalIndex-1, // last index
+ lastSourceI, // last source
+ this.messageSources[lastSourceI].size()-1);
+ this.oldFirstPositionList.add(lastSourceIndex);
+ this.newFirstPositionList.add(lastSourceIndex);
+ }
+ }
+
+ @Override
+ public int size() throws IOException {
+ return this.size;
+ }
+
+ @Override
+ public CharSequence getURI() {
+ return this.uri;
+ }
+
+ @Override
+ public CharSequence getFormat() {
+ return this.format;
+ }
+
+ @Override
+ public Iterator getMessagesAsCharSequence() throws IOException {
+ return new MessageMergerCharSequenceIterator(new MessageMergerIterator(true));
+ }
+
+ private class MessageMergerCharSequenceIterator implements Iterator {
+ private final MessageMergerIterator iter;
+
+ MessageMergerCharSequenceIterator(MessageMergerIterator iter) {
+ this.iter = iter;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return this.iter.hasNext();
+ }
+
+ @Override
+ public CharSequence next() {
+ return new String(this.iter.next());
+ }
+ }
+
+ @Override
+ public Iterator getMessages() throws IOException {
+ return new MessageMergerIterator(true);
+ }
+
+ private class MessageMergerIterator implements Iterator {
+ private final boolean chronologically;
+ private int currentPosition;
+ private byte[] lookAheadMessage = null;
+
+ MessageMergerIterator(boolean chronologically) {
+ this.chronologically = chronologically;
+
+ }
+
+ @Override
+ public boolean hasNext() {
+ if(lookAheadMessage == null) {
+ // try
+ try {
+ this.lookAheadMessage = ASAPMessagesMerger.this.getMessage(currentPosition++, chronologically);
+ } catch (ASAPException | IOException e) {
+ return false;
+ }
+ }
+ return (this.lookAheadMessage != null);
+ }
+
+ @Override
+ public byte[] next() {
+ if (this.lookAheadMessage != null) {
+ if (this.hasNext()) {
+ byte[] temp = this.lookAheadMessage;
+ this.lookAheadMessage = null;
+ return temp;
+ }
+ }
+
+ throw new NoSuchElementException("no more messages");
+ }
+ }
+
+ @Override
+ public CharSequence getMessageAsCharSequence(int position, boolean chronologically) throws ASAPException, IOException {
+ return new String(this.getMessage(position, chronologically));
+ }
+
+ /**
+ The list is organized like this: Each entry describes a position of the merged sources: wantedPosition.
+ It also describes source (actually the index of the source: sourceIndex) and position of the message
+ in the source (positionInSource). There is not necessarily and entry for each wantedPosition - to keep
+ that list short.
+
+ A entry is made if the list was empty. There will always be an entry for wantedPosition == 0. Another entry
+ will only added if source has changed. Assumed we would have two sources (A and B), first messages come from
+ A, follow by B again and so forth, list would look like this: (wantedPosition: 0, A, 0) Both positions will be
+ 0 in the first entry. Next entry could be: (4, B, 0). Message for position comes from source B index 0. But
+ where come message at 1, 2 and 3? From A. There was no change of source, no entry was made. We avoid a series of
+ entries like: (1, A, 1), (2, A, 2), (3, A, 3). They can easily be calculated.
+ */
+ private SourceIndex getSourceIndex(int position, List indexList) {
+ if(indexList.isEmpty()) return null; // not yet initialized?
+ SourceIndex previousIndexEntry = null;
+ int i = 0;
+ do {
+ if(indexList.size() <= i) return null;
+ SourceIndex indexEntry = indexList.get(i++);
+
+ if(indexEntry.wantedPosition == position) return indexEntry; // found match
+
+ if(previousIndexEntry != null
+ && previousIndexEntry.wantedPosition < position
+ && position < indexEntry.wantedPosition) {
+ // we are within a range.
+ int offsetIndex = previousIndexEntry.wantedPosition;
+ int steps = position - offsetIndex;
+ return new SourceIndex(position,
+ previousIndexEntry.sourceIndex,
+ previousIndexEntry.positionInSource + steps);
+ }
+
+ previousIndexEntry = indexEntry;
+ } while(previousIndexEntry.wantedPosition < position); // we have still a chance to find anything
+
+ return null; // there is no entry
+ }
+
+ private static final int FALSE = 0;
+ private static final int TRUE = 1;
+ private byte[][][] lookAheadMessages = new byte[2][][]; // actual look ahead message
+ private SourceIndex[][] lookAheadSourceIndex = new SourceIndex[2][]; // describes position etc. of previous
+
+ private byte[][] getLookAheadMessages(boolean chronologically) {
+ byte[][] a = chronologically ? this.lookAheadMessages[TRUE] : this.lookAheadMessages[FALSE];
+
+ if(a == null) { // not yet initialized
+ a = new byte[this.messageSources.length][];
+ if(chronologically) this.lookAheadMessages[TRUE] = a;
+ else this.lookAheadMessages[FALSE] = a;
+ }
+
+ return a;
+ }
+
+ private SourceIndex[] getLookAheadSourceIndex(boolean chronologically) {
+ SourceIndex[] s = chronologically ? this.lookAheadSourceIndex[TRUE] : this.lookAheadSourceIndex[FALSE];
+
+ if(s == null) { // not yet initialized
+ s = new SourceIndex[this.messageSources.length];
+ if(chronologically) this.lookAheadSourceIndex[TRUE] = s;
+ else this.lookAheadSourceIndex[FALSE] = s;
+ }
+
+ return s;
+ }
+
+ private boolean lookAheadSettedUp = false;
+ private SourceIndex lookAhead(int position, List indexList, boolean chronologically)
+ throws ASAPException, IOException {
+
+ int wantedLookAheadPosition = 0;
+
+ if(!indexList.isEmpty()) { // we already made a look ahead
+ // get last entry
+ SourceIndex sourceIndex = indexList.get(indexList.size() - 1);
+
+ // check for your own stupidity - last position is before our wanted position - we would not be here otherwise
+ if (sourceIndex != null && sourceIndex.wantedPosition >= position)
+ throw new ASAPException("internal error - look ahead algorithm buggy");
+
+ wantedLookAheadPosition = sourceIndex.wantedPosition + 1;
+ }
+
+ byte[][] lookAheadMessages = this.getLookAheadMessages(chronologically);
+ SourceIndex[] lookAheadSourceIndexArray = this.getLookAheadSourceIndex(chronologically);
+
+ if(!this.lookAheadSettedUp) { // setup
+ // set it up - read first message from each non empty source
+ this.lookAheadSettedUp = true;
+ for (int i = 0; i < this.messageSources.length; i++) {
+ lookAheadMessages[i] = this.messageSources[i].getMessage(0, chronologically);
+ lookAheadSourceIndexArray[i] = new SourceIndex(-1, i, 0);
+ }
+ }
+
+ // find message for next position.
+ SourceIndex previousSourceIndex = null;
+ SourceIndex foundSourceIndex = null;
+
+ boolean lastSourceIndexAdded;
+ do {
+ int bestSourceIndex = -1; // init source index 0 wins?
+ lastSourceIndexAdded = false; // not yet at least
+
+ for (int i = 0; i < this.messageSources.length; i++) {
+ if(lookAheadMessages[i] == null) continue; // nothing to do in this round
+ if(bestSourceIndex == -1) {
+ // guess we have a winner without opponent
+ bestSourceIndex = i;
+ continue;
+ }
+
+ boolean previousEarlier =
+ this.messageCompare.earlier(lookAheadMessages[bestSourceIndex], lookAheadMessages[i]);
+
+ /*
+ previous earlier | chronologically | what wins?
+ -----------------------------------------------
+ true true no change
+ false true i is better
+ true false i is better
+ false false no change
+ */
+
+ if (previousEarlier != chronologically) { bestSourceIndex = i; }
+ }
+
+ if(bestSourceIndex == -1) // failure in algorithm - should not happen due to test of size()..
+ throw new ASAPException("no more message - cannot look ahead");
+
+ // we have a winner
+ foundSourceIndex = lookAheadSourceIndexArray[bestSourceIndex];
+
+ // now we can tell at what overall position this message is
+ foundSourceIndex.wantedPosition = wantedLookAheadPosition;
+
+ if(previousSourceIndex != null) {
+ if(previousSourceIndex.sourceIndex != foundSourceIndex.sourceIndex) {
+ // remember previous - we have a change in sources
+ indexList.add(foundSourceIndex);
+ lastSourceIndexAdded = true;
+ }
+ } else {
+ indexList.add(foundSourceIndex);
+ lastSourceIndexAdded = true;
+ }
+
+ // prepare next round
+ previousSourceIndex = foundSourceIndex;
+
+ // read ahead - if possible
+ lookAheadSourceIndexArray[bestSourceIndex] = null;
+ lookAheadMessages[bestSourceIndex] = null;
+ int nextPositionInSource = foundSourceIndex.positionInSource + 1;
+ try {
+ lookAheadMessages[bestSourceIndex] =
+ messageSources[bestSourceIndex].getMessage(nextPositionInSource, chronologically);
+
+ // remember read ahead
+ lookAheadSourceIndexArray[bestSourceIndex] =
+ new SourceIndex(-1, // we cannot tell yet
+ bestSourceIndex, nextPositionInSource); // we know where it comes from
+ }
+ catch(Exception e) {
+ // no more messages
+ }
+ } while(position > wantedLookAheadPosition++);
+
+ // remember this in any case
+ if(!lastSourceIndexAdded) indexList.add(foundSourceIndex);
+
+ return foundSourceIndex;
+ }
+
+ private List getIndexList(boolean chronologically) {
+ return chronologically ? oldFirstPositionList : newFirstPositionList;
+ }
+
+ private SourceIndex getSourceIndex(int position, boolean chronologically) throws ASAPException, IOException {
+ if(position >= this.size)
+ throw new ASAPException("position index must not exceed total number of messages: "
+ + position + " >= " + this.size);
+
+ SourceIndex sourceIndex;
+ List usedList = this.getIndexList(chronologically);
+
+ sourceIndex = this.getSourceIndex(position, usedList);
+
+ if(sourceIndex == null) {
+ // cache miss
+ sourceIndex = this.lookAhead(position, usedList, chronologically);
+ }
+ if(sourceIndex == null) {
+ // still nothing
+ throw new ASAPException("no message at position: " + position);
+ }
+
+ return sourceIndex;
+ }
+
+ @Override
+ public byte[] getMessage(int position, boolean chronologically) throws ASAPException, IOException {
+ SourceIndex sourceIndex = this.getSourceIndex(position, chronologically);
+ return this.messageSources[sourceIndex.sourceIndex].getMessage(
+ sourceIndex.positionInSource, chronologically);
+ }
+
+ @Override
+ public ASAPChunk getChunk(int position, boolean chronologically) throws IOException, ASAPException {
+ SourceIndex sourceIndex = this.getSourceIndex(position, chronologically);
+ return this.messageSources[sourceIndex.sourceIndex].getChunk(sourceIndex.positionInSource, chronologically);
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSender.java b/src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSender.java
new file mode 100644
index 0000000..7b21127
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSender.java
@@ -0,0 +1,20 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.ASAPException;
+
+import java.io.IOException;
+import java.util.Set;
+
+public interface ASAPOnlineMessageSender {
+ void sendASAPAssimilateMessage(CharSequence format, CharSequence urlTarget, Set recipients,
+ byte[] messageAsBytes, int era) throws IOException, ASAPException;
+
+ void sendASAPAssimilateMessage(CharSequence format, CharSequence urlTarget, CharSequence recipient,
+ byte[] messageAsBytes, int era) throws IOException, ASAPException;
+
+ void sendASAPAssimilateMessage(CharSequence format, CharSequence urlTarget, byte[] messageAsBytes, int era)
+ throws IOException, ASAPException;
+
+ void sendASAPAssimilateMessage(CharSequence format, CharSequence urlTarget, byte[] messageAsBytes)
+ throws IOException, ASAPException;
+}
diff --git a/src/net/sharksystem/asap/ASAPOnlineMessageSenderEngineSide.java b/src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSenderEngineSide.java
similarity index 53%
rename from src/net/sharksystem/asap/ASAPOnlineMessageSenderEngineSide.java
rename to src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSenderEngineSide.java
index 639b414..b7d3546 100644
--- a/src/net/sharksystem/asap/ASAPOnlineMessageSenderEngineSide.java
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSenderEngineSide.java
@@ -1,10 +1,12 @@
-package net.sharksystem.asap;
+package net.sharksystem.asap.engine;
+import net.sharksystem.asap.ASAP;
+import net.sharksystem.asap.ASAPException;
import net.sharksystem.asap.protocol.ASAPConnection;
import net.sharksystem.asap.protocol.ASAPOnlineMessageSource;
import net.sharksystem.asap.protocol.ASAP_1_0;
import net.sharksystem.asap.protocol.ASAP_Modem_Impl;
-import net.sharksystem.asap.util.Log;
+import net.sharksystem.utils.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -14,7 +16,7 @@
public class ASAPOnlineMessageSenderEngineSide extends ASAPAbstractOnlineMessageSender
implements ASAPOnlineMessageSource, ASAPOnlineMessageSender {
- private final MultiASAPEngineFS multiEngine;
+ private final ASAPInternalPeer multiEngine;
private final ASAP_1_0 protocol = new ASAP_Modem_Impl();
// connections and their remote peer (recipients)
@@ -23,72 +25,77 @@ public class ASAPOnlineMessageSenderEngineSide extends ASAPAbstractOnlineMessage
// message for recipients
private Map> messages = new HashMap<>();
- public ASAPOnlineMessageSenderEngineSide(MultiASAPEngineFS multiEngine) {
+ public ASAPOnlineMessageSenderEngineSide(ASAPInternalPeer multiEngine) {
this.multiEngine = multiEngine;
}
- public void sendASAPAssimilate(CharSequence format, CharSequence uri, byte[] messageAsBytes, int era)
+ public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, byte[] messageAsBytes)
+ throws IOException, ASAPException {
+ this.sendASAPAssimilateMessage(format, uri, messageAsBytes, ASAPEngineFS.DEFAULT_INIT_ERA);
+ }
+
+ public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, byte[] messageAsBytes, int era)
throws IOException, ASAPException {
Set onlinePeers = this.multiEngine.getOnlinePeers();
if(onlinePeers == null || onlinePeers.size() < 1) {
- System.out.println(this.getLogStart() + "no online peers");
+ Log.writeLog(this, "no online peers");
throw new ASAPException("no online peers");
}
Set onlinePeerList = new HashSet<>();
for(CharSequence peerName : onlinePeers) {
onlinePeerList.add(peerName);
- System.out.println(this.getLogStart() + peerName + "is online");
+ Log.writeLog(this, peerName + " is online");
}
- this.sendASAPAssimilate(format, uri, onlinePeerList, messageAsBytes, era);
+ this.sendASAPAssimilateMessage(format, uri, onlinePeerList, messageAsBytes, era);
}
- public void sendASAPAssimilate(CharSequence format, CharSequence uri, Set recipients,
- byte[] messageAsBytes, int era) throws IOException, ASAPException {
+ public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, Set receiver,
+ byte[] messageAsBytes, int era) throws IOException, ASAPException {
- if(recipients == null || recipients.size() < 1) {
- this.sendASAPAssimilate(format, uri, messageAsBytes, era);
+ if(receiver == null || receiver.size() < 1) {
+ // replace empty recipient list with list of online peers.
+ this.sendASAPAssimilateMessage(format, uri, messageAsBytes, era);
+ return;
}
StringBuilder sb = Log.startLog(this);
sb.append("sendASAPAssimilate(format: ");
sb.append(format);
- sb.append(", uri: ");
+ sb.append("| uri: ");
sb.append(uri);
- sb.append(", era: ");
- sb.append(era);
- sb.append(", #recipients: ");
- sb.append(recipients.size());
- sb.append(", messageBytes: ");
- sb.append(new String(messageAsBytes));
+ sb.append("| era: ");
+ if(era != ASAP.TRANSIENT_ERA) sb.append(era);
+ else sb.append("transient");
+ sb.append("| #receiver: ");
+ if(receiver != null) sb.append(receiver.size());
+ else sb.append("null");
+ sb.append("| length: ");
+ sb.append(messageAsBytes.length);
sb.append(")");
- System.out.println(sb.toString());
+ Log.writeLog(this, sb.toString());
- // each message can have multiple recipients. Iterate
+ // each message can have multiple receiver. Iterate
- // is there an open connection to each of the recipients.
+ // is there an open connection to each of the receiver.
boolean foundAll = true; // optimism captain :)
- for(CharSequence recipient : recipients) {
+ for(CharSequence recipient : receiver) {
sb = Log.startLog(this);
sb.append("try to find connection for recipient: ");
sb.append(recipient);
- System.out.println(sb.toString());
+ Log.writeLog(this, sb.toString());
if(multiEngine.existASAPConnection(recipient)) {
ASAPConnection asapConnection = multiEngine.getASAPConnection(recipient);
sb = Log.startLog(this);
- sb.append("got asap connection, subscribe / and store message");
- System.out.println(sb.toString());
-
- // subscribe and remember it
- asapConnection.addOnlineMessageSource(this);
- this.connectionPeers.put(asapConnection, recipient);
+ sb.append("got asap connection, subscribe and store message");
+ Log.writeLog(this, sb.toString());
// serialize message for this recipient
ByteArrayOutputStream asapPDUBytes = new ByteArrayOutputStream();
- protocol.assimilate(this.multiEngine.getOwner(), recipient, format, uri, era, null, // no offsets
- messageAsBytes, asapPDUBytes, asapConnection.isSigned());
+ this.protocol.assimilate(this.multiEngine.getOwner(), recipient, format, uri, era, null, // no offsets
+ null, messageAsBytes, asapPDUBytes, asapConnection.isSigned());
// I guess maps are synchronized
List messageList = this.messages.get(recipient);
@@ -99,30 +106,33 @@ public void sendASAPAssimilate(CharSequence format, CharSequence uri, Set messageList = this.messages.get(recipient);
- System.out.println(this.getLogStart() + " send message(s) to " + recipient);
+ Log.writeLog(this, this.getLogStart() + "send message(s) to " + recipient + " via: "
+ + os.getClass().getSimpleName());
while(!messageList.isEmpty()) {
- System.out.println(this.getLogStart() + " send message to " + recipient);
- System.out.println(this.getLogStart() + "outstream: " + os.getClass().getSimpleName());
- os.write(messageList.remove(0));
- System.out.println(this.getLogStart() + "wrote");
+ byte[] messageBytes = messageList.remove(0);
+ os.write(messageBytes);
+ Log.writeLog(this, "wrote pure bytes: " + messageBytes.length);
}
this.messages.remove(recipient);
diff --git a/src/net/sharksystem/asap/ASAPProtocolEngine.java b/src/main/java/net/sharksystem/asap/engine/ASAPProtocolEngine.java
similarity index 51%
rename from src/net/sharksystem/asap/ASAPProtocolEngine.java
rename to src/main/java/net/sharksystem/asap/engine/ASAPProtocolEngine.java
index dfdcb8d..a1a0569 100644
--- a/src/net/sharksystem/asap/ASAPProtocolEngine.java
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPProtocolEngine.java
@@ -1,9 +1,10 @@
-package net.sharksystem.asap;
+package net.sharksystem.asap.engine;
+import net.sharksystem.asap.ASAPEncounterConnectionType;
+import net.sharksystem.asap.ASAPException;
import net.sharksystem.asap.protocol.ASAP_1_0;
import net.sharksystem.asap.protocol.ASAP_AssimilationPDU_1_0;
import net.sharksystem.asap.protocol.ASAP_Interest_PDU_1_0;
-import net.sharksystem.asap.protocol.ASAP_OfferPDU_1_0;
import java.io.IOException;
import java.io.InputStream;
@@ -13,30 +14,32 @@
* @author thsc
*/
public interface ASAPProtocolEngine {
- void handleASAPInterest(ASAP_Interest_PDU_1_0 asapInterest, ASAP_1_0 protocol, OutputStream os)
+ void handleASAPInterest(ASAP_Interest_PDU_1_0 asapInterest, ASAP_1_0 protocol,
+ String encounteredPeer, OutputStream os, ASAPEncounterConnectionType connectionType)
throws ASAPException, IOException;
- void handleASAPOffer(ASAP_OfferPDU_1_0 asapOffer, ASAP_1_0 protocol, OutputStream os)
- throws ASAPException, IOException;
-
- void handleASAPAssimilate(ASAP_AssimilationPDU_1_0 asap_assimilation, ASAP_1_0 protocol,
- InputStream is, OutputStream os, ASAPChunkReceivedListener listener)
+ void handleASAPAssimilate(ASAP_AssimilationPDU_1_0 asapAssimilationPDU, ASAP_1_0 protocolModem,
+ String encounteredPeer, InputStream is, OutputStream os,
+ ASAPEncounterConnectionType connectionType,
+ ASAPChunkAssimilatedListener listener)
throws ASAPException, IOException;
/**
* Chunks are (tried to be) delivered to their recipients during each encounter
* with another peer. After successful delivery, recipient is withdrawn from recipient
- * list to prevent mutliple delivery.
+ * list to prevent multiple delivery.
*
* If this flag is set, chunk are removed permanently if their are delivered
- * to all their recipients. If no set, they remain intact.
+ * to all their recipients. There are kept in local storage otherwise.
* @param drop
*/
- void setDropDeliveredChunks(boolean drop) throws IOException;
+ void setBehaviourDropDeliveredChunks(boolean drop) throws IOException;
/**
* engine can deliver local message but also received messages - default false - send no received messages
* @param on
*/
- void setSendReceivedChunks(boolean on) throws IOException;
+ void setBehaviourAllowRouting(boolean on) throws IOException;
+
+ boolean routingAllowed();
}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPSingleProcessOnlineMessageSender.java b/src/main/java/net/sharksystem/asap/engine/ASAPSingleProcessOnlineMessageSender.java
new file mode 100644
index 0000000..4e9c8f0
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPSingleProcessOnlineMessageSender.java
@@ -0,0 +1,45 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.protocol.ASAPConnection;
+import net.sharksystem.asap.protocol.ASAPOnlineMessageSource;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Set;
+
+public class ASAPSingleProcessOnlineMessageSender
+ extends ASAPAbstractOnlineMessageSender implements ASAPOnlineMessageSource {
+
+ private final ASAPOnlineMessageSenderEngineSide asapOnlineMessageSenderEngineSide;
+
+ public ASAPSingleProcessOnlineMessageSender(ASAPInternalPeer multiEngine, ASAPInternalStorage source) {
+ this.attachToSource(source);
+ this.asapOnlineMessageSenderEngineSide = new ASAPOnlineMessageSenderEngineSide(multiEngine);
+ }
+
+ @Override
+ public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, Set recipients,
+ byte[] messageAsBytes, int era) throws IOException, ASAPException {
+
+ this.asapOnlineMessageSenderEngineSide.sendASAPAssimilateMessage(
+ format, uri, recipients, messageAsBytes, era);
+ }
+
+ public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, byte[] messageAsBytes)
+ throws IOException, ASAPException {
+ this.sendASAPAssimilateMessage(format, uri, messageAsBytes, ASAPEngineFS.DEFAULT_INIT_ERA);
+ }
+
+ @Override
+ public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, byte[] messageAsBytes, int era)
+ throws IOException, ASAPException {
+
+ this.asapOnlineMessageSenderEngineSide.sendASAPAssimilateMessage(format, uri, messageAsBytes, era);
+ }
+
+ @Override
+ public void sendStoredMessages(ASAPConnection asapConnection, OutputStream os) throws IOException {
+ this.asapOnlineMessageSenderEngineSide.sendStoredMessages(asapConnection, os);
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPStorageImpl.java b/src/main/java/net/sharksystem/asap/engine/ASAPStorageImpl.java
new file mode 100644
index 0000000..fcd7fd4
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPStorageImpl.java
@@ -0,0 +1,10 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.ASAPChunkStorage;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.protocol.ASAP_1_0;
+
+import java.io.IOException;
+
+public abstract class ASAPStorageImpl implements ASAPInternalStorage {
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPUndecryptableMessageHandler.java b/src/main/java/net/sharksystem/asap/engine/ASAPUndecryptableMessageHandler.java
new file mode 100644
index 0000000..c85fb1f
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/ASAPUndecryptableMessageHandler.java
@@ -0,0 +1,13 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.crypto.ASAPCryptoAlgorithms;
+
+public interface ASAPUndecryptableMessageHandler {
+ String FORMAT_UNDECRYPTABLE_MESSAGES = "asap/undecryptable";
+ String URI_UNDECRYPTABLE_MESSAGES = "asap://undecryptable";
+ /**
+ * Peer can (and should) receive encrypted messages without being receiver. A peer is not able
+ * to encrypt that message but could store and forward. That is what ASAP is about.
+ */
+ void handleUndecryptableMessage(ASAPCryptoAlgorithms.EncryptedMessagePackage encryptedMessage, CharSequence receiver);
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/CryptoControl.java b/src/main/java/net/sharksystem/asap/engine/CryptoControl.java
new file mode 100644
index 0000000..2b9021b
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/CryptoControl.java
@@ -0,0 +1,7 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.protocol.ASAP_PDU_1_0;
+
+public interface CryptoControl {
+ boolean allowed2Process(ASAP_PDU_1_0 pdu);
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/DefaultSecurityAdministrator.java b/src/main/java/net/sharksystem/asap/engine/DefaultSecurityAdministrator.java
new file mode 100644
index 0000000..3c024d1
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/DefaultSecurityAdministrator.java
@@ -0,0 +1,110 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.protocol.ASAP_AssimilationPDU_1_0;
+import net.sharksystem.asap.protocol.ASAP_PDU_1_0;
+import net.sharksystem.asap.crypto.ASAPPoint2PointCryptoSettings;
+import net.sharksystem.utils.Log;
+
+import java.io.IOException;
+
+public class DefaultSecurityAdministrator implements ASAPCommunicationSetting,
+ ASAPEnginePermissionSettings, CryptoControl, ASAPPoint2PointCryptoSettings {
+
+ private boolean receivedMessageMustBeEncrypted = false;
+ private boolean receivedMessagesMustBeSigned = false;
+ private boolean sendEncrypted = false;
+ private boolean sendSigned;
+
+ @Override
+ public void setRememberEncounteredPeers(boolean on) throws IOException {
+
+ }
+
+ @Override
+ public void setReceivedMessagesMustBeEncrypted(boolean on) throws IOException {
+ this.receivedMessageMustBeEncrypted = on;
+ }
+
+ @Override
+ public void setReceivedMessagesMustBeSigned(boolean on) throws IOException {
+ this.receivedMessagesMustBeSigned = on;
+ }
+
+ @Override
+ public void setSetAllowedRemotePeers(AllowedRemotePeers safetyLevel) {
+
+ }
+
+ @Override
+ public boolean setRevealEngineFormat(String peerName) {
+ return false;
+ }
+
+ @Override
+ public boolean setSendOpenMessages(String peerName) {
+ return false;
+ }
+
+ @Override
+ public boolean allowedToCreateChannel(ASAP_AssimilationPDU_1_0 asapAssimilationPDU) {
+ return true; // it is a dummy
+ }
+
+ @Override
+ public void setSendEncryptedMessages(boolean on) {
+ this.sendEncrypted = on;
+ }
+
+ @Override
+ public void setSendSignedMessages(boolean on) {
+ this.sendSigned = on;
+ }
+
+ @Override
+ public boolean allowed2Process(ASAP_PDU_1_0 pdu) {
+ if(this.receivedMessagesMustBeSigned && !pdu.signed()) {
+ Log.writeLog(this, "checked: " + pdu);
+ Log.writeLog(this, "not signed");
+ return false;
+ }
+ if(this.receivedMessageMustBeEncrypted && !pdu.encrypted()) {
+ Log.writeLog(this, "checked: " + pdu);
+ Log.writeLog(this, "not encrypted");
+ return false;
+ }
+
+ Log.writeLog(this, "ok");
+ return true;
+ }
+
+ private String getLogStart() {
+ return this.getClass().getSimpleName() + ": ";
+ }
+
+ @Override
+ public boolean mustEncrypt() {
+ return this.sendEncrypted;
+ }
+
+ @Override
+ public boolean mustSign() {
+ return this.sendSigned;
+ }
+
+ /*
+ private boolean encryptedMessagesOnly = false;
+ private boolean signedMessagesOnly = false;
+ private boolean sendEncrypted = false;
+ private boolean sendSigned;
+
+ */
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(this.getLogStart());
+ sb.append("recEncrypted: " + this.receivedMessageMustBeEncrypted);
+ sb.append(" | recSigned: " + this.receivedMessagesMustBeSigned);
+ sb.append(" | sendEncrypted: " + this.sendEncrypted);
+ sb.append(" | sendSigned: " + this.sendSigned);
+ return sb.toString();
+ }
+}
diff --git a/src/net/sharksystem/asap/EngineSetting.java b/src/main/java/net/sharksystem/asap/engine/EngineSetting.java
similarity index 60%
rename from src/net/sharksystem/asap/EngineSetting.java
rename to src/main/java/net/sharksystem/asap/engine/EngineSetting.java
index e7f13bb..8316c27 100644
--- a/src/net/sharksystem/asap/EngineSetting.java
+++ b/src/main/java/net/sharksystem/asap/engine/EngineSetting.java
@@ -1,11 +1,11 @@
-package net.sharksystem.asap;
+package net.sharksystem.asap.engine;
public class EngineSetting {
public final CharSequence folder;
- public ASAPChunkReceivedListener listener;
+ public ASAPChunkAssimilatedListener listener;
public ASAPEngine engine;
- EngineSetting(CharSequence folder, ASAPChunkReceivedListener listener) {
+ EngineSetting(CharSequence folder, ASAPChunkAssimilatedListener listener) {
this.folder = folder;
this.listener = listener;
}
diff --git a/src/main/java/net/sharksystem/asap/engine/MessageIter.java b/src/main/java/net/sharksystem/asap/engine/MessageIter.java
new file mode 100644
index 0000000..82eba0a
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/MessageIter.java
@@ -0,0 +1,32 @@
+package net.sharksystem.asap.engine;
+
+import java.io.FileNotFoundException;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+public class MessageIter implements Iterator {
+ private final List byteMessages;
+ private int nextIndex;
+ private String nextString;
+
+
+ public MessageIter(List byteMessages) throws FileNotFoundException {
+ this.byteMessages = byteMessages;
+ this.nextIndex = 0;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return this.byteMessages.size() > nextIndex;
+ }
+
+ @Override
+ public String next() {
+ if (!this.hasNext()) {
+ throw new NoSuchElementException("no more messages");
+ }
+
+ return new String(this.byteMessages.get(nextIndex++));
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/engine/MessagesContainer.java b/src/main/java/net/sharksystem/asap/engine/MessagesContainer.java
new file mode 100644
index 0000000..1e0f90e
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/engine/MessagesContainer.java
@@ -0,0 +1,12 @@
+package net.sharksystem.asap.engine;
+
+import net.sharksystem.asap.ASAPHop;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+
+public interface MessagesContainer {
+ void addMessage(InputStream is, long length) throws IOException;
+ void setASAPHopList(List asapHopList) throws IOException;
+}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/ASAPChannelContentChangedListenerManager.java b/src/main/java/net/sharksystem/asap/listenermanager/ASAPChannelContentChangedListenerManager.java
new file mode 100644
index 0000000..00beaa7
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/listenermanager/ASAPChannelContentChangedListenerManager.java
@@ -0,0 +1,71 @@
+package net.sharksystem.asap.listenermanager;
+
+import net.sharksystem.asap.*;
+
+import java.util.HashMap;
+
+public class ASAPChannelContentChangedListenerManager implements ASAPChannelContentChangedListenerManagement {
+ private HashMap> listenerMap =
+ new HashMap();
+
+ @Override
+ public void addASAPChannelContentChangedListener(CharSequence format, ASAPChannelContentChangedListener listener) {
+ GenericListenerImplementation listenerList = this.listenerMap.get(format);
+ if(listenerList == null) {
+ listenerList = new GenericListenerImplementation();
+ this.listenerMap.put(format, listenerList);
+ }
+
+ listenerList.addListener(listener);
+ }
+
+ @Override
+ public void removeASAPChannelContentChangedListener(CharSequence format, ASAPChannelContentChangedListener listener) {
+ GenericListenerImplementation listenerList = this.listenerMap.get(format);
+ if(listenerList != null) {
+ listenerList.removeListener(listener);
+ }
+ }
+
+ public int getNumberListener() {
+ if(this.listenerMap == null) return 0;
+ return this.listenerMap.size();
+ }
+
+ public void removeAllListeners() {
+ // reset
+ this.listenerMap = new HashMap();
+ }
+
+ public void notifyChanged(CharSequence format, CharSequence uri, int era) {
+
+ this.notifyChanged(format, uri, era, false);
+ }
+
+ public void notifyChanged(CharSequence format, CharSequence uri, int era, boolean useThreads) {
+
+ GenericListenerImplementation listenerList = this.listenerMap.get(format);
+ if(listenerList != null) {
+ ASAPChannelContentChangedListenerManager.ASAPChannelContentChangedNotifier notifier
+ = new ASAPChannelContentChangedListenerManager.ASAPChannelContentChangedNotifier(format, uri, era);
+
+ listenerList.notifyAll(notifier, useThreads);
+ }
+ }
+
+ public class ASAPChannelContentChangedNotifier implements GenericNotifier {
+ private CharSequence format;
+ private CharSequence uri;
+ private int era;
+
+ ASAPChannelContentChangedNotifier(CharSequence format, CharSequence uri, int era) {
+ this.format = format;
+ this.uri = uri;
+ this.era = era;
+ }
+
+ public void doNotify(ASAPChannelContentChangedListener listener) {
+ listener.asapChannelContentChanged(this.format, this.uri, this.era);
+ }
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/ASAPEnvironmentChangesListenerManager.java b/src/main/java/net/sharksystem/asap/listenermanager/ASAPEnvironmentChangesListenerManager.java
new file mode 100644
index 0000000..6d54f61
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/listenermanager/ASAPEnvironmentChangesListenerManager.java
@@ -0,0 +1,34 @@
+package net.sharksystem.asap.listenermanager;
+
+import net.sharksystem.asap.ASAPEnvironmentChangesListener;
+import net.sharksystem.asap.ASAPEnvironmentChangesListenerManagement;
+import net.sharksystem.utils.Log;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class ASAPEnvironmentChangesListenerManager
+ extends GenericListenerImplementation
+ implements ASAPEnvironmentChangesListenerManagement {
+
+ @Override
+ public void addASAPEnvironmentChangesListener(ASAPEnvironmentChangesListener changesListener) {
+ this.addListener(changesListener);
+ }
+
+ @Override
+ public void removeASAPEnvironmentChangesListener(ASAPEnvironmentChangesListener changesListener) {
+ this.removeListener(changesListener);
+ }
+
+ public void notifyListeners(Set peerList) {
+ if(peerList == null) peerList = new HashSet<>();
+
+ if(this.listenerList == null || this.listenerList.isEmpty()) return;
+
+ // make a copy of that list
+ for(ASAPEnvironmentChangesListener listener : this.listenerList) {
+ if(listener != null) listener.onlinePeersChanged(new HashSet<>(peerList));
+ }
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/ASAPMessageReceivedListenerManager.java b/src/main/java/net/sharksystem/asap/listenermanager/ASAPMessageReceivedListenerManager.java
new file mode 100644
index 0000000..41de9d0
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/listenermanager/ASAPMessageReceivedListenerManager.java
@@ -0,0 +1,87 @@
+package net.sharksystem.asap.listenermanager;
+
+import net.sharksystem.asap.*;
+import net.sharksystem.utils.Log;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+
+public class ASAPMessageReceivedListenerManager implements ASAPMessageReceivedListenerManagement {
+ private HashMap> listenerMap =
+ new HashMap();
+
+ @Override
+ public void addASAPMessageReceivedListener(CharSequence format, ASAPMessageReceivedListener listener) {
+ GenericListenerImplementation listenerList = this.listenerMap.get(format);
+ if(listenerList == null) {
+ listenerList = new GenericListenerImplementation();
+ this.listenerMap.put(format, listenerList);
+ }
+
+ listenerList.addListener(listener);
+ }
+
+ @Override
+ public void removeASAPMessageReceivedListener(CharSequence format, ASAPMessageReceivedListener listener) {
+ GenericListenerImplementation listenerList = this.listenerMap.get(format);
+ if(listenerList != null) {
+ listenerList.removeListener(listener);
+ }
+ }
+
+ @Override
+ public int getNumberListener() {
+ if(this.listenerMap == null) return 0;
+ return this.listenerMap.size();
+ }
+
+ public void removeAllListeners() {
+ // reset
+ this.listenerMap = new HashMap();
+ }
+
+ public void notifyReceived(CharSequence format, ASAPMessages asapMessage,
+ String senderE2E, // E2E part
+ List asapHopList) {
+
+ this.notifyReceived(format, asapMessage, false, senderE2E, asapHopList);
+ }
+
+ public void notifyReceived(CharSequence format, ASAPMessages asapMessage, boolean useThreads,
+ String senderE2E, List asapHopList) {
+
+ GenericListenerImplementation listenerList = this.listenerMap.get(format);
+ if(listenerList != null) {
+ ASAPMessageReceivedNotifier asapMessageReceivedNotifier
+ = new ASAPMessageReceivedNotifier(asapMessage, senderE2E, asapHopList);
+
+ listenerList.notifyAll(asapMessageReceivedNotifier, useThreads);
+ }
+ }
+
+ public class ASAPMessageReceivedNotifier implements GenericNotifier {
+ private final ASAPMessages asapMessage;
+ private final String senderE2E;
+ private List asapHopList;
+
+ ASAPMessageReceivedNotifier(ASAPMessages asapMessage,
+ String senderE2E,
+ List asapHopList) {
+
+ this.asapMessage = asapMessage;
+ this.senderE2E = senderE2E;
+ this.asapHopList = asapHopList;
+ }
+
+ public void doNotify(ASAPMessageReceivedListener listener) {
+ try {
+ //Log.writeLog(this, "notify: " + listener.getClass().getSimpleName());
+ listener.asapMessagesReceived(this.asapMessage, this.senderE2E, this.asapHopList);
+ } catch (IOException e) {
+ System.err.println("error when notifying about received asap message: "
+ + e.getLocalizedMessage());
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/GenericListenerImplementation.java b/src/main/java/net/sharksystem/asap/listenermanager/GenericListenerImplementation.java
new file mode 100644
index 0000000..e2d4507
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/listenermanager/GenericListenerImplementation.java
@@ -0,0 +1,47 @@
+package net.sharksystem.asap.listenermanager;
+
+import net.sharksystem.utils.Log;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class GenericListenerImplementation {
+ protected List listenerList = new ArrayList();
+
+ protected void addListener(L listener) {
+ if(!this.listenerList.contains(listener)) {
+ this.listenerList.add(listener);
+ }
+ }
+
+ protected void removeListener(L listener) {
+ this.listenerList.remove(listener);
+ }
+
+ public void removeAllListeners() {
+ this.listenerList = new ArrayList();
+ }
+
+ public void notifyAll(GenericNotifier notifier, boolean useThreads) {
+ for(L listener : this.listenerList) {
+ if(useThreads) {
+ new Thread (new Runnable() {
+ @Override
+ public void run() { notifier.doNotify(listener); }
+ }).start();
+ } else { // no threads
+ notifier.doNotify(listener);
+ }
+ }
+ }
+
+ protected void log(String msg) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(Log.startLog(this));
+ sb.append(": ");
+ sb.append(msg);
+
+ Log.writeLog(this, sb.toString());
+ }
+
+}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/GenericNotifier.java b/src/main/java/net/sharksystem/asap/listenermanager/GenericNotifier.java
new file mode 100644
index 0000000..9bd2fa5
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/listenermanager/GenericNotifier.java
@@ -0,0 +1,8 @@
+package net.sharksystem.asap.listenermanager;
+
+public interface GenericNotifier {
+ /**
+ * run specific notification
+ */
+ void doNotify(L listener);
+}
diff --git a/src/net/sharksystem/asap/management/ASAPManagementCreateASAPStorageMessage.java b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementCreateASAPStorageMessage.java
similarity index 87%
rename from src/net/sharksystem/asap/management/ASAPManagementCreateASAPStorageMessage.java
rename to src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementCreateASAPStorageMessage.java
index 8df31fe..2e813ae 100644
--- a/src/net/sharksystem/asap/management/ASAPManagementCreateASAPStorageMessage.java
+++ b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementCreateASAPStorageMessage.java
@@ -1,4 +1,4 @@
-package net.sharksystem.asap.management;
+package net.sharksystem.asap.listenermanager.management;
import java.util.Set;
diff --git a/src/net/sharksystem/asap/management/ASAPManagementMessage.java b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessage.java
similarity index 98%
rename from src/net/sharksystem/asap/management/ASAPManagementMessage.java
rename to src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessage.java
index dc56904..8bef338 100644
--- a/src/net/sharksystem/asap/management/ASAPManagementMessage.java
+++ b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessage.java
@@ -1,4 +1,4 @@
-package net.sharksystem.asap.management;
+package net.sharksystem.asap.listenermanager.management;
import net.sharksystem.asap.ASAPException;
import net.sharksystem.asap.protocol.ASAP_1_0;
diff --git a/src/net/sharksystem/asap/management/ASAPManagementMessageHandler.java b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessageHandler.java
similarity index 73%
rename from src/net/sharksystem/asap/management/ASAPManagementMessageHandler.java
rename to src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessageHandler.java
index 6204fa7..fa91269 100644
--- a/src/net/sharksystem/asap/management/ASAPManagementMessageHandler.java
+++ b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessageHandler.java
@@ -1,15 +1,22 @@
-package net.sharksystem.asap.management;
-
-import net.sharksystem.asap.*;
+package net.sharksystem.asap.listenermanager.management;
+
+import net.sharksystem.asap.ASAPHop;
+import net.sharksystem.asap.ASAPMessages;
+import net.sharksystem.asap.engine.ASAPInternalChunk;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.engine.ASAPInternalStorage;
+import net.sharksystem.asap.ASAPChunkStorage;
+import net.sharksystem.asap.engine.*;
import net.sharksystem.asap.protocol.ASAP_1_0;
+import net.sharksystem.utils.Log;
import java.io.IOException;
import java.util.*;
-public class ASAPManagementMessageHandler implements ASAPChunkReceivedListener {
- private final MultiASAPEngineFS multiASAPEngine;
+public class ASAPManagementMessageHandler implements ASAPChunkAssimilatedListener {
+ private final ASAPInternalPeer multiASAPEngine;
- public ASAPManagementMessageHandler(MultiASAPEngineFS multiASAPEngine) throws IOException, ASAPException {
+ public ASAPManagementMessageHandler(ASAPInternalPeer multiASAPEngine) throws IOException, ASAPException {
this.multiASAPEngine = multiASAPEngine;
}
@@ -36,16 +43,19 @@ CharSequence getURI(Set recipients) throws IOException, ASAPExcept
return null;
}
- public void chunkReceived(String format, String sender, String uri, int era) {
- System.out.println(this.getLogStart()
- + "handle received chunk (format|sender|uri|era) " + format + sender + "|" + uri + "|" + era);
+ @Override
+ public void chunkStored(String format, String senderE2E, String uri, int era,
+ List asapHop) throws IOException {
+
+ Log.writeLog(this,
+ "handle received chunk (format|senderE2E|uri|era) " + format + senderE2E + "|" + uri + "|" + era);
try {
ASAPEngine asapManagementEngine = multiASAPEngine.getEngineByFormat(ASAP_1_0.ASAP_MANAGEMENT_FORMAT);
- ASAPChunkStorage incomingChunkStorage = asapManagementEngine.getIncomingChunkStorage(sender);
- ASAPChunk chunk = incomingChunkStorage.getChunk(uri, era);
- Iterator messageIter = chunk.getMessagesAsBytes();
- System.out.println(this.getLogStart() + "iterate management messages");
+ ASAPChunkStorage incomingChunkStorage = asapManagementEngine.getReceivedChunksStorage(senderE2E);
+ ASAPInternalChunk chunk = incomingChunkStorage.getChunk(uri, era);
+ Iterator messageIter = chunk.getMessages();
+ Log.writeLog(this, "iterate management messages");
while(messageIter.hasNext()) {
byte[] message = messageIter.next();
Set recipients = this.handleASAPManagementMessage(message);
@@ -57,7 +67,7 @@ public void chunkReceived(String format, String sender, String uri, int era) {
sendUri = createUniqueUri();
}
// write message
- System.out.println(this.getLogStart() + "add received message locally: ");
+ Log.writeLog(this, "add received message locally: ");
asapManagementEngine.add(sendUri, message);
if(setUpRecipients) {
@@ -65,20 +75,25 @@ public void chunkReceived(String format, String sender, String uri, int era) {
this.recipientUris.put(recipients, sendUri);
}
}
- System.out.println(this.getLogStart() + "done iterating management messages");
+ Log.writeLog(this, "done iterating management messages");
// remove incoming messages - handled
- asapManagementEngine.getIncomingChunkStorage(sender).dropChunks(era);
- System.out.println(this.getLogStart() + "incoming asap management messages dropped");
+ asapManagementEngine.getReceivedChunksStorage(senderE2E).dropChunks(era);
+ Log.writeLog(this, "incoming asap management messages dropped");
} catch (ASAPException | IOException e) {
- System.out.println("could get asap management engine but received chunk - looks like a bug");
+ Log.writeLog(this, "could get asap management engine but received chunk - looks like a bug");
}
}
+ @Override
+ public void transientMessagesReceived(ASAPMessages transientMessages, ASAPHop asapHop) throws IOException {
+ Log.writeLogErr(this, "transientChunkReceived not yet implement");
+ }
+
private Set handleASAPManagementMessage(byte[] message) throws ASAPException, IOException {
StringBuilder b = new StringBuilder();
b.append(this.getLogStart());
b.append("start processing asap management pdu");
- System.out.println(b.toString());
+ Log.writeLog(this, b.toString());
ASAPManagementCreateASAPStorageMessage asapManagementCreateASAPStorageMessage =
ASAPManagementMessage.parseASAPManagementMessage(message);
@@ -111,7 +126,7 @@ private Set handleASAPManagementMessage(byte[] message) throws ASA
b.append(recipients.size());
// find storage / app - can throw an exception - that's ok
- ASAPStorage asapStorage = this.multiASAPEngine.getEngineByFormat(format);
+ ASAPInternalStorage asapStorage = this.multiASAPEngine.getEngineByFormat(format);
if(asapStorage.channelExists(channelUri)) {
Set existingChannelRecipientsList = asapStorage.getRecipients(channelUri);
@@ -140,7 +155,7 @@ private Set handleASAPManagementMessage(byte[] message) throws ASA
}
// else - channel does not exist - create by setting recipients
- System.out.println(this.getLogStart() + "create channel: " + b.toString());
+ Log.writeLog(this, "create channel: " + b.toString());
asapStorage.createChannel(owner, channelUri, recipients);
return receivedRecipients;
diff --git a/src/net/sharksystem/asap/management/ASAPManagementStorage.java b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorage.java
similarity index 87%
rename from src/net/sharksystem/asap/management/ASAPManagementStorage.java
rename to src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorage.java
index f21caa7..93cf6a6 100644
--- a/src/net/sharksystem/asap/management/ASAPManagementStorage.java
+++ b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorage.java
@@ -1,4 +1,4 @@
-package net.sharksystem.asap.management;
+package net.sharksystem.asap.listenermanager.management;
import net.sharksystem.asap.ASAPException;
diff --git a/src/net/sharksystem/asap/management/ASAPManagementStorageImpl.java b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorageImpl.java
similarity index 90%
rename from src/net/sharksystem/asap/management/ASAPManagementStorageImpl.java
rename to src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorageImpl.java
index 9c43e8a..17c8408 100644
--- a/src/net/sharksystem/asap/management/ASAPManagementStorageImpl.java
+++ b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorageImpl.java
@@ -1,6 +1,6 @@
-package net.sharksystem.asap.management;
+package net.sharksystem.asap.listenermanager.management;
-import net.sharksystem.asap.ASAPEngine;
+import net.sharksystem.asap.engine.ASAPEngine;
import net.sharksystem.asap.ASAPException;
import java.io.IOException;
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPConnection.java b/src/main/java/net/sharksystem/asap/protocol/ASAPConnection.java
new file mode 100644
index 0000000..8f66e66
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/protocol/ASAPConnection.java
@@ -0,0 +1,21 @@
+package net.sharksystem.asap.protocol;
+
+import net.sharksystem.asap.ASAPEncounterConnectionType;
+
+public interface ASAPConnection {
+ CharSequence getEncounteredPeer();
+
+ void addOnlineMessageSource(ASAPOnlineMessageSource source);
+ void removeOnlineMessageSource(ASAPOnlineMessageSource source);
+
+ void addASAPConnectionListener(ASAPConnectionListener asapConnectionListener);
+
+ void removeASAPConnectionListener(ASAPConnectionListener asapConnectionListener);
+
+ boolean isSigned();
+
+ ASAPEncounterConnectionType getASAPEncounterConnectionType();
+
+ // terminate that connection - does not effect the underlying connections established e.g. with Bluetooth
+ void kill();
+}
diff --git a/src/net/sharksystem/asap/protocol/ASAPConnectionListener.java b/src/main/java/net/sharksystem/asap/protocol/ASAPConnectionListener.java
similarity index 75%
rename from src/net/sharksystem/asap/protocol/ASAPConnectionListener.java
rename to src/main/java/net/sharksystem/asap/protocol/ASAPConnectionListener.java
index 0a0ea21..f7abfc5 100644
--- a/src/net/sharksystem/asap/protocol/ASAPConnectionListener.java
+++ b/src/main/java/net/sharksystem/asap/protocol/ASAPConnectionListener.java
@@ -4,9 +4,8 @@ public interface ASAPConnectionListener {
/**
* Called when first message was read from remote peer.
* The session started.
- * @param peer
*/
- void asapConnectionStarted(String peer, ASAPConnection connection);
+ void asapConnectionStarted(String remotePeerName, ASAPConnection connection);
void asapConnectionTerminated(Exception terminatingException, ASAPConnection connection);
}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPCryptoMessage.java b/src/main/java/net/sharksystem/asap/protocol/ASAPCryptoMessage.java
new file mode 100644
index 0000000..de76424
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/protocol/ASAPCryptoMessage.java
@@ -0,0 +1,228 @@
+package net.sharksystem.asap.protocol;
+
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPSecurityException;
+import net.sharksystem.asap.crypto.ASAPKeyStore;
+import net.sharksystem.asap.crypto.ASAPCryptoAlgorithms;
+import net.sharksystem.asap.utils.ASAPSerialization;
+import net.sharksystem.utils.Log;
+
+import java.io.*;
+
+class ASAPCryptoMessage {
+ private boolean encrypted;
+ private boolean sign;
+ private CharSequence recipient;
+ private ASAPKeyStore ASAPKeyStore;
+ private byte cmd;
+
+ private OutputStream effectiveOS;
+ private OutputStream realOS;
+ private ByteArrayOutputStream outputStreamCopy;
+ private InputStreamCopy inputStreamCopy;
+ private ASAPCryptoAlgorithms.EncryptedMessagePackage encryptedMessagePackage;
+
+ ASAPCryptoMessage(ASAPKeyStore ASAPKeyStore) {
+ this.ASAPKeyStore = ASAPKeyStore;
+ }
+
+ ASAPCryptoMessage(byte cmd, OutputStream os, boolean sign, boolean encrypted,
+ CharSequence recipient,
+ ASAPKeyStore ASAPKeyStore)
+ throws ASAPSecurityException {
+
+ this.cmd = cmd;
+ this.realOS = os;
+ this.effectiveOS = os; // still this one
+ this.ASAPKeyStore = ASAPKeyStore;
+ this.recipient = recipient;
+ this.encrypted = encrypted;
+ this.sign = sign;
+
+ if(encrypted || sign) {
+ // we need some basic crypto parameters
+ if(ASAPKeyStore == null) {
+ throw new ASAPSecurityException("cannot encrypt or sign without cryptp parameters / key store");
+ }
+ this.setupCopyOutputStream();
+ }
+
+ if(encrypted) {
+ // mark encryption in command - rest will be encrypted
+ this.cmd += ASAP_1_0.ENCRYPTED_CMD;
+ if(this.recipient == null) {
+ throw new ASAPSecurityException("cannot encrypt message with no specified receiver - fatal, give up");
+ }
+ }
+
+ if(sign) {
+ // signing needs a private key - check of available
+ if(ASAPKeyStore.getPrivateKey() == null) {
+ throw new ASAPSecurityException("asap message is to be signed but no private key - fatal, give up");
+ }
+ }
+ }
+
+ private void setupCopyOutputStream() {
+ if(this.outputStreamCopy == null) {
+ this.outputStreamCopy = new ByteArrayOutputStream();
+ // pud will make a detour
+ this.effectiveOS = this.outputStreamCopy;
+ }
+ }
+
+ public void sendCmd() throws IOException {
+ // send cmd in clear
+ PDU_Impl.sendCmd(this.cmd, this.realOS);
+ }
+
+ public OutputStream getOutputStream() {
+ return this.effectiveOS;
+ }
+
+ public void finish() throws ASAPSecurityException {
+ if(this.sign) {
+ try {
+ // get message as bytes
+ byte[] asapMessageAsBytes = this.outputStreamCopy.toByteArray();
+ // produce signature
+ byte[] signatureBytes = ASAPCryptoAlgorithms.sign(asapMessageAsBytes, this.ASAPKeyStore);
+
+ if(this.encrypted) {
+ // have to store it - message and signature will be encrypted
+ ASAPSerialization.writeByteArray(signatureBytes, this.outputStreamCopy);
+ } else {
+ // no encryption planned - write clear to stream
+ this.realOS.write(asapMessageAsBytes);
+ ASAPSerialization.writeByteArray(signatureBytes, this.realOS);
+ }
+ } catch (IOException e) {
+ throw new ASAPSecurityException(this.getLogStart(), e);
+ }
+ }
+
+ if(this.encrypted) {
+ // get maybe signed asap message
+ byte[] asapMessageAsBytes = this.outputStreamCopy.toByteArray();
+
+ ASAPCryptoAlgorithms.writeEncryptedMessagePackage(
+ asapMessageAsBytes, this.recipient, this.ASAPKeyStore, this.realOS);
+ }
+ }
+
+ public CharSequence getReceiver() {
+ return this.recipient;
+ }
+
+ ////////////////////////////////// verify
+ private class InputStreamCopy extends InputStream {
+ private final InputStream is;
+ ByteArrayOutputStream copy = new ByteArrayOutputStream();
+
+ InputStreamCopy(byte[] bytes, InputStream is) throws IOException {
+ // add byte if any
+ if(bytes != null && bytes.length > 0) {
+ copy.write(bytes);
+ }
+
+ this.is = is;
+ }
+
+ @Override
+ public int read() throws IOException {
+ int read = is.read();
+ copy.write(read);
+ return read;
+ }
+
+ byte[] getCopy() {
+ return copy.toByteArray();
+ }
+ }
+
+ public InputStream setupCopyInputStream(int flags, InputStream is)
+ throws IOException {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+// if(writeInt) {
+// PDU_Impl.sendFlags(flags, baos);
+// }
+
+ PDU_Impl.sendFlags(flags, baos);
+ //baos.write(flags);
+
+ this.inputStreamCopy = new InputStreamCopy(baos.toByteArray(), is);
+ return this.inputStreamCopy;
+ }
+
+ public boolean verify(String sender, InputStream is) throws IOException, ASAPException {
+ // try to get senders' public key
+ byte[] signedData = this.inputStreamCopy.getCopy();
+ byte[] signatureBytes = ASAPSerialization.readByteArray(is);
+ // debug break
+ boolean wasVerified =
+ ASAPCryptoAlgorithms.verify(signedData, signatureBytes, sender, this.ASAPKeyStore);
+
+ return wasVerified;
+ }
+
+ ////////////////////////////////// decrypt
+
+ /**
+ * Simple idea: We read anything from stream and keep a copy. Later, we figure out
+ * if we can encrypt that message or not. Either way, we can keep and redistribute a copy.
+ *
+ *
+ * @param cmd
+ * @param is
+ * @return
+ * @throws IOException
+ * @throws ASAPException
+ */
+ public boolean initDecryption(byte cmd, InputStream is) throws IOException, ASAPException {
+ // make a copy of encrypted message - it is redundant. Same data in encryptedMessagePackage
+ //InputStream copyStream = this.setupCopyInputStream(cmd, is);
+
+ this.encryptedMessagePackage =
+ ASAPCryptoAlgorithms.parseEncryptedMessagePackage(is);
+ // ASAPCryptoAlgorithms.parseEncryptedMessagePackage(copyStream);
+
+ if(this.ASAPKeyStore == null) {
+ Log.writeLog(this, "no keystore set: cannot handle encrypted messages");
+ return false;
+ }
+
+ if(this.ASAPKeyStore.isOwner(this.encryptedMessagePackage.getReceiver())) {
+ return true;
+ }
+
+ return false;
+ }
+
+ ASAPCryptoAlgorithms.EncryptedMessagePackage getEncryptedMessage() throws ASAPSecurityException {
+ return this.encryptedMessagePackage;
+ /*
+ if(this.inputStreamCopy == null) {
+ throw new ASAPSecurityException(
+ this.getLogStart() + "no copy made, maybe forgot to initialize decryption?");
+ }
+
+ return this.inputStreamCopy.getCopy();
+ */
+ }
+
+ public InputStream doDecryption() throws ASAPSecurityException {
+ if(this.encryptedMessagePackage == null) {
+ throw new ASAPSecurityException("forgot to initialize decryption? There are no data");
+ }
+
+ byte[] decryptedBytes =
+ ASAPCryptoAlgorithms.decryptPackage(this.encryptedMessagePackage, this.ASAPKeyStore);
+
+ return new ByteArrayInputStream(decryptedBytes);
+ }
+
+ private String getLogStart() {
+ return this.getClass().getSimpleName() + ": ";
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPEncounterList.java b/src/main/java/net/sharksystem/asap/protocol/ASAPEncounterList.java
new file mode 100644
index 0000000..2729637
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/protocol/ASAPEncounterList.java
@@ -0,0 +1,30 @@
+package net.sharksystem.asap.protocol;
+
+import net.sharksystem.asap.ASAPException;
+
+import java.io.IOException;
+import java.util.Set;
+
+public interface ASAPEncounterList {
+ /**
+ * Provides a set of peer id. There is record of a previous encounter with those peers.
+ * @return
+ */
+ Set getEncounteredPeers();
+
+ /**
+ * Provide era of last encounter with a peer. The local era, the counting of this peer is returned.
+ * @param peerID
+ * @return
+ * @throws ASAPException There is not such peerID
+ */
+ int getLocalMostRecentEra(CharSequence peerID) throws ASAPException;
+
+ /**
+ * Provide the most era from a most recent chunk received by this peer.
+ * @param peerID
+ * @return
+ * @throws ASAPException There is not such peerID
+ */
+ int getTheirMostRecentEra(CharSequence peerID) throws ASAPException, IOException;
+}
diff --git a/src/net/sharksystem/asap/protocol/ASAPExecTimeExceededException.java b/src/main/java/net/sharksystem/asap/protocol/ASAPExecTimeExceededException.java
similarity index 100%
rename from src/net/sharksystem/asap/protocol/ASAPExecTimeExceededException.java
rename to src/main/java/net/sharksystem/asap/protocol/ASAPExecTimeExceededException.java
diff --git a/src/net/sharksystem/asap/protocol/ASAPOnlineMessageSource.java b/src/main/java/net/sharksystem/asap/protocol/ASAPOnlineMessageSource.java
similarity index 59%
rename from src/net/sharksystem/asap/protocol/ASAPOnlineMessageSource.java
rename to src/main/java/net/sharksystem/asap/protocol/ASAPOnlineMessageSource.java
index 690908f..d5c9a5f 100644
--- a/src/net/sharksystem/asap/protocol/ASAPOnlineMessageSource.java
+++ b/src/main/java/net/sharksystem/asap/protocol/ASAPOnlineMessageSource.java
@@ -4,5 +4,5 @@
import java.io.OutputStream;
public interface ASAPOnlineMessageSource {
- void sendMessages(ASAPConnection asapConnection, OutputStream os) throws IOException;
+ void sendStoredMessages(ASAPConnection asapConnection, OutputStream os) throws IOException;
}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPProtocolEngine.java b/src/main/java/net/sharksystem/asap/protocol/ASAPProtocolEngine.java
new file mode 100644
index 0000000..35166f1
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/protocol/ASAPProtocolEngine.java
@@ -0,0 +1,66 @@
+package net.sharksystem.asap.protocol;
+
+import net.sharksystem.asap.engine.ASAPUndecryptableMessageHandler;
+import net.sharksystem.asap.crypto.ASAPKeyStore;
+import net.sharksystem.utils.Log;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+public abstract class ASAPProtocolEngine {
+ protected final ASAP_1_0 protocol;
+ protected final InputStream is;
+ protected final OutputStream os;
+ protected final ASAPUndecryptableMessageHandler undecryptableMessageHandler;
+ protected final ASAPKeyStore ASAPKeyStore;
+
+ public ASAPProtocolEngine(InputStream is, OutputStream os, ASAP_1_0 protocol,
+ ASAPUndecryptableMessageHandler undecryptableMessageHandler,
+ ASAPKeyStore ASAPKeyStore) {
+ /*
+ this.is = new ISWrapper(is);
+ this.os = new OSWrapper(os);
+ */
+ this.is = is;
+ this.os = os;
+ this.protocol = protocol;
+ this.undecryptableMessageHandler = undecryptableMessageHandler;
+ this.ASAPKeyStore = ASAPKeyStore;
+
+ Log.writeLog(this, "constructor", "is: "
+ + is.getClass().getSimpleName() + " | os: " + os.getClass().getSimpleName());
+ }
+
+ private class ISWrapper extends InputStream {
+ private final InputStream is;
+
+ ISWrapper(InputStream is) {
+ this.is = is;
+ }
+ @Override
+ public int read() throws IOException {
+ return is.read();
+ }
+ public void close() {
+ Log.writeLog(this, "wrapper: close called");
+ }
+ }
+
+ private class OSWrapper extends OutputStream {
+ private final OutputStream os;
+
+ OSWrapper(OutputStream is) {
+ this.os = is;
+ }
+
+ @Override
+ public void write(int b) throws IOException {
+ this.os.write(b);
+ }
+
+ public void close() {
+ Log.writeLog(this, "wrapper: close called");
+ }
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPSessionImpl.java b/src/main/java/net/sharksystem/asap/protocol/ASAPSessionImpl.java
new file mode 100644
index 0000000..b149a29
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/protocol/ASAPSessionImpl.java
@@ -0,0 +1,557 @@
+package net.sharksystem.asap.protocol;
+
+import net.sharksystem.asap.ASAP;
+import net.sharksystem.asap.ASAPEncounterConnectionType;
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.engine.ASAPEngine;
+import net.sharksystem.asap.engine.ASAPInternalPeer;
+import net.sharksystem.asap.engine.ASAPUndecryptableMessageHandler;
+import net.sharksystem.asap.engine.EngineSetting;
+import net.sharksystem.utils.Log;
+import net.sharksystem.asap.crypto.ASAPKeyStore;
+
+import java.io.*;
+import java.util.ArrayList;
+import java.util.List;
+
+public class ASAPSessionImpl extends ASAPProtocolEngine
+ implements ASAPConnection, Runnable, ThreadFinishedListener {
+
+ private final List asapConnectionListener;
+ private final ASAPInternalPeer asapInternalPeer;
+ private final ThreadFinishedListener threadFinishedListener;
+ private final boolean encrypt;
+ private final boolean sign;
+ private final ASAPEncounterConnectionType connectionType;
+ private Thread managementThread = null;
+ private final long maxExecutionTime;
+ private String encounteredPeer;
+
+ private List onlineMessageSources = new ArrayList<>();
+ private Thread threadWaiting4StreamsLock;
+ private boolean terminated = false;
+
+ public ASAPSessionImpl(InputStream is, OutputStream os, ASAPInternalPeer asapInternalPeer,
+ ASAP_1_0 protocol, ASAPUndecryptableMessageHandler unencryptableMessageHandler,
+ ASAPKeyStore ASAPKeyStore,
+ long maxExecutionTime, ASAPConnectionListener asapConnectionListener,
+ ThreadFinishedListener threadFinishedListener,
+ boolean encrypt, boolean sign, ASAPEncounterConnectionType connectionType) {
+
+ super(is, os, protocol, unencryptableMessageHandler, ASAPKeyStore);
+
+ this.asapInternalPeer = asapInternalPeer;
+ this.maxExecutionTime = maxExecutionTime;
+ this.asapConnectionListener = new ArrayList<>();
+ this.asapConnectionListener.add(asapConnectionListener);
+
+ this.threadFinishedListener = threadFinishedListener;
+ this.encrypt = encrypt;
+ this.sign = sign;
+ this.connectionType = connectionType;
+ }
+
+ public void addASAPConnectionListener(ASAPConnectionListener asapConnectionListener) {
+ this.asapConnectionListener.add(asapConnectionListener);
+ }
+
+ public void removeASAPConnectionListener(ASAPConnectionListener asapConnectionListener) {
+ this.asapConnectionListener.remove(asapConnectionListener);
+ }
+
+ private String getLogParameter() {
+ String s = "to: ";
+ s += this.encounteredPeer != null ? this.encounteredPeer : "unknown yet";
+ return s;
+ }
+
+ private void setEncounteredPeer(String remotePeerName) {
+ if(this.encounteredPeer == null) {
+
+ this.encounteredPeer = remotePeerName;
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(this.getLogParameter());
+ sb.append("set remotePeerName after reading first asap message: ");
+ sb.append(remotePeerName);
+ Log.startLog(this, sb.toString());
+
+ if(this.asapConnectionListener != null) {
+ for(ASAPConnectionListener l : this.asapConnectionListener) {
+ l.asapConnectionStarted(remotePeerName, this);
+ }
+ }
+ }
+ }
+
+ @Override
+ public CharSequence getEncounteredPeer() {
+ return this.encounteredPeer;
+ }
+
+ @Override
+ public void removeOnlineMessageSource(ASAPOnlineMessageSource source) {
+ this.onlineMessageSources.remove(source);
+ }
+
+ public boolean isSigned() {
+ return false;
+ }
+
+ @Override
+ public ASAPEncounterConnectionType getASAPEncounterConnectionType() {
+ return this.connectionType;
+ }
+
+ @Override
+ public void kill() {
+ this.kill(new ASAPException("kill called from outside asap connection"));
+ }
+
+ public void kill(Exception e) {
+ if(!this.terminated) {
+ this.terminated = true;
+ // kill reader - proved to be useful in a bluetooth environment
+ if(this.pduReader != null && this.pduReader.isAlive()) {
+ this.pduReader.interrupt();
+ }
+ if(this.managementThread != null && this.managementThread.isAlive()) {
+ this.managementThread.interrupt();
+ }
+ // inform listener
+ if (this.asapConnectionListener != null) {
+ for(ASAPConnectionListener l : this.asapConnectionListener) {
+ l.asapConnectionTerminated(e, this);
+ }
+ }
+
+ if (this.threadFinishedListener != null) {
+ this.threadFinishedListener.finished(Thread.currentThread());
+ }
+ }
+ }
+
+ @Override
+ public void finished(Thread t) {
+ if(this.managementThread != null) {
+ this.managementThread.interrupt();
+ }
+ }
+
+ private void terminate(String message, Throwable t) {
+ // write log
+ StringBuilder sb = new StringBuilder();
+ sb.append(message);
+ if(t != null) {
+ sb.append(" | issued by: ");
+ sb.append(t.getClass().getSimpleName());
+ sb.append(": ");
+ sb.append(t.getLocalizedMessage());
+ // debugging
+ //t.printStackTrace();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t.printStackTrace(new PrintStream(baos));
+ sb.append("\n>>>>>>>>>>>>> stack trace:\n");
+ sb.append(baos.toString());
+ sb.append("<<<<<<<<<<<< stack trace");
+ }
+ Log.writeLog(this, this.getLogParameter(), sb.toString());
+
+ this.kill();
+ }
+
+ private void sendOnlineMessages() throws IOException {
+ List copy = this.onlineMessageSources;
+ this.onlineMessageSources = new ArrayList<>();
+ while(!copy.isEmpty()) {
+ ASAPOnlineMessageSource asapOnline = copy.remove(0);
+ StringBuilder sb = new StringBuilder();
+ sb.append("going to send online message");
+ Log.writeLog(this, this.getLogParameter(), sb.toString());
+ asapOnline.sendStoredMessages(this, this.os);
+ }
+ }
+
+ private class OnlineMessageSenderThread extends Thread {
+ public void run() {
+ try {
+ // get exclusive access to streams
+ Log.writeLog(this, getLogParameter(), "online sender is going to wait for stream access");
+ wait4ExclusiveStreamsAccess();
+ Log.writeLog(this, getLogParameter(), "online sender got stream access");
+ sendOnlineMessages();
+ // prepare a graceful death
+ onlineMessageSenderThread = null;
+ // are new message waiting in the meantime?
+ checkRunningOnlineMessageSender();
+ } catch (IOException e) {
+ terminate("could not write data into stream", e);
+ }
+ finally {
+ Log.writeLog(this, getLogParameter(), "online sender releases lock");
+ releaseStreamsLock();
+ }
+ }
+ }
+
+ private OnlineMessageSenderThread onlineMessageSenderThread = null;
+ private ASAPPDUReader pduReader = null;
+ Thread executor = null;
+
+ @Override
+ public void addOnlineMessageSource(ASAPOnlineMessageSource source) {
+ this.onlineMessageSources.add(source);
+ this.checkRunningOnlineMessageSender();
+ }
+
+ private synchronized void checkRunningOnlineMessageSender() {
+ if(this.onlineMessageSenderThread == null
+ && this.onlineMessageSources != null && this.onlineMessageSources.size() > 0) {
+ this.onlineMessageSenderThread = new OnlineMessageSenderThread();
+ this.onlineMessageSenderThread.start();
+ }
+ }
+
+ public void run() {
+ ASAP_1_0 protocol = new ASAP_Modem_Impl(this.ASAPKeyStore, this.undecryptableMessageHandler);
+
+ try {
+ // let engine write their interest - at least management interest is sent which als introduces
+ // this peer to the other one
+ this.asapInternalPeer.pushInterests(this.os);
+ } catch (IOException | ASAPException e) {
+ this.terminate("error when pushing interest: ", e);
+ //e.printStackTrace();
+ return;
+ }
+
+ /////////////////////////////// read
+ while (!this.terminated) {
+ this.pduReader = new ASAPPDUReader(protocol, is, this);
+ Throwable unexpectedThrowable = null;
+ try {
+ Log.writeLog(this, this.getLogParameter(), "start reading");
+ this.runObservedThread(pduReader, this.maxExecutionTime);
+ } catch (ASAPExecTimeExceededException e) {
+ Log.writeLog(this, this.getLogParameter(), "reading on stream took longer than allowed");
+ }
+ catch(Throwable t) {
+ unexpectedThrowable = t;
+ Log.writeLog(this, this.getLogParameter(), "while reading PDU: "
+ + t.getClass().getSimpleName() + ": " + t.getLocalizedMessage());
+ }
+
+ Log.writeLog(this, this.getLogParameter(), "back from reading");
+ if(terminated) break; // thread could be killed in the meantime
+
+ if (unexpectedThrowable != null || pduReader.getIoException() != null || pduReader.getAsapException() != null) {
+ Log.writeLog(this, this.getLogParameter(), "connection broken");
+
+ Throwable problem = pduReader.getIoException() != null ?
+ pduReader.getIoException() : pduReader.getAsapException();
+
+ if(problem == null) problem = unexpectedThrowable;
+
+ try {
+ Log.writeLog(this, this.getLogParameter(), "close input stream");
+ this.is.close();
+ } catch (IOException exception) {
+ Log.writeLog(this, this.getLogParameter(),
+ "tried to close stream after exception caught: " + exception.getLocalizedMessage());
+ }
+
+ this.terminate("problem when reading from stream (close asap session and stream): ", problem);
+ break;
+ }
+
+ ASAP_PDU_1_0 asappdu = pduReader.getASAPPDU();
+ /////////////////////////////// process
+ if(asappdu != null) {
+ Log.writeLog(this, this.getLogParameter(),
+ "read valid pdu, remember meeting this peer and going to process pdu");
+ this.setEncounteredPeer(asappdu.getSender());
+
+ EngineSetting engineSettings = null;
+ try {
+ engineSettings = this.asapInternalPeer.getEngineSettings(asappdu.getFormat());
+ } catch(ASAPException e) {
+ // can happen with transient messages
+ Log.writeLog(this, this.getLogParameter(), "no engine setting - set defaults");
+ }
+
+ try {
+ if(engineSettings == null) {
+ ASAPEngine asapEngine = this.asapInternalPeer.getASAPEngine(asappdu.getFormat());
+ engineSettings = this.asapInternalPeer.getEngineSettings(asappdu.getFormat());
+ engineSettings.engine = asapEngine;
+ Log.writeLog(this, this.getLogParameter(), engineSettings.toString());
+ }
+
+ this.executor = new ASAPPDUExecutor(asappdu,
+ this.encounteredPeer, this.is, this.os, engineSettings,
+ protocol,this.connectionType, this);
+
+ // get exclusive access to streams
+ Log.writeLog(this, this.getLogParameter(), "asap pdu executor going to wait for stream access");
+ this.wait4ExclusiveStreamsAccess();
+ try {
+ Log.writeLog(this, this.getLogParameter(), "asap pdu executor got stream access - process pdu");
+ this.runObservedThread(executor, maxExecutionTime);
+ } catch (ASAPExecTimeExceededException e) {
+ Log.writeLog(this, this.getLogParameter(), "asap pdu processing took longer than allowed");
+ this.terminate("asap pdu processing took longer than allowed", e);
+ break;
+ } finally {
+ // wake waiting thread if any
+ this.releaseStreamsLock();
+ Log.writeLog(this, this.getLogParameter(), "asap pdu executor release locks");
+ }
+ } catch (ASAPException | IOException e) {
+ // Log.writeLog(this, this.getLogParameter(), "problem when executing asap received pdu: " + e);
+ this.terminate("problem when executing asap received pdu: ", e);
+ }
+ }
+ }
+
+ // asap session ended
+ }
+
+ private Thread threadUsingStreams = null;
+ private synchronized Thread getThreadUsingStreams(Thread t) {
+ if(this.threadUsingStreams == null) {
+ this.threadUsingStreams = t;
+ return null;
+ }
+
+ return this.threadUsingStreams;
+ }
+
+ // why not simply synchronized(this) { ... }?? OK, that code works but looks complicated (thsc42)
+ private void wait4ExclusiveStreamsAccess() {
+ // synchronize with other thread using streams
+ Thread threadUsingStreams = this.getThreadUsingStreams(Thread.currentThread());
+
+ // got lock - go ahead
+ if(threadUsingStreams == null) {
+ return;
+ }
+
+ // there is another thread - wait until it dies
+ do {
+ Log.writeLog(this, this.getLogParameter(), "enter waiting loop for exclusive stream access");
+ // wait
+ try {
+ this.threadWaiting4StreamsLock = Thread.currentThread();
+ threadUsingStreams.join();
+ } catch (InterruptedException e) {
+ Log.writeLog(this, this.getLogParameter(), "woke up from join");
+ }
+ finally {
+ this.threadWaiting4StreamsLock = null;
+ }
+ // try again
+ Log.writeLog(this, this.getLogParameter(), "try to get streams access again");
+ threadUsingStreams = this.getThreadUsingStreams(Thread.currentThread());
+ } while(threadUsingStreams != null);
+ Log.writeLog(this, this.getLogParameter(), "leave waiting loop for exclusive stream access");
+ }
+
+ private void releaseStreamsLock() {
+ this.threadUsingStreams = null; // take me out
+ if(this.threadWaiting4StreamsLock != null) {
+ Log.writeLog(this, this.getLogParameter(), "wake waiting thread");
+ this.threadWaiting4StreamsLock.interrupt();
+ }
+ }
+
+ private void runObservedThread(Thread t, long maxExecutionTime) throws ASAPExecTimeExceededException {
+ this.managementThread = Thread.currentThread();
+ t.start();
+
+ // wait for reader
+ try {
+ Thread.sleep(maxExecutionTime);
+ } catch (InterruptedException e) {
+ // was woken up by thread - that's good
+ return;
+ }
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("thread (");
+ sb.append(t.getClass().getSimpleName());
+ sb.append(") exceeded max execution time of ");
+ sb.append(maxExecutionTime);
+ sb.append(" ms");
+
+ throw new ASAPExecTimeExceededException(sb.toString());
+ }
+
+ private class ASAPPDUExecutor extends Thread {
+ private final ASAP_PDU_1_0 asapPDU;
+ private final InputStream is;
+ private final OutputStream os;
+ private final EngineSetting engineSetting;
+ private final ASAP_1_0 protocol;
+ private final ThreadFinishedListener threadFinishedListener;
+ private final String encounteredPeer;
+ private final ASAPEncounterConnectionType connectionType;
+
+ public ASAPPDUExecutor(ASAP_PDU_1_0 asapPDU, String encounteredPeer, InputStream is, OutputStream os,
+ EngineSetting engineSetting, ASAP_1_0 protocol,
+ ASAPEncounterConnectionType connectionType, ThreadFinishedListener threadFinishedListener) {
+ this.asapPDU = asapPDU;
+ this.encounteredPeer = encounteredPeer;
+ this.is = is;
+ this.os = os;
+ this.engineSetting = engineSetting;
+ this.protocol = protocol;
+ this.connectionType = connectionType;
+ this.threadFinishedListener = threadFinishedListener;
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(getLogParameter());
+ sb.append("ASAPPDUExecutor: ");
+ sb.append("engine: " + engineSetting.engine.getClass().getSimpleName() + " | ");
+ if(engineSetting.listener != null) {
+ sb.append("listener: " + engineSetting.listener.getClass().getSimpleName() + " | ");
+ }
+ sb.append("folder: " + engineSetting.folder);
+
+ Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(), sb.toString());
+ }
+
+ private void finish() {
+ if(this.threadFinishedListener != null) {
+ this.threadFinishedListener.finished(this);
+ }
+ }
+
+ public void run() {
+ if(engineSetting.engine == null) {
+ Log.writeLogErr(this, ASAPSessionImpl.this.getLogParameter(),
+ "ASAPPDUExecutor called without engine set - fatal");
+ this.finish();
+ return;
+ }
+
+ Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
+ "ASAPPDUExecutor calls engine: " + engineSetting.engine.getClass().getSimpleName());
+
+ try {
+ switch (asapPDU.getCommand()) {
+ // TODO add encrypt / sign as parameter..
+ case ASAP_1_0.INTEREST_CMD:
+ Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
+ "ASAPPDUExecutor call handleASAPInterest");
+ engineSetting.engine.handleASAPInterest(
+ (ASAP_Interest_PDU_1_0) asapPDU, this.protocol,
+ this.encounteredPeer,
+ this.os,
+ this.connectionType);
+ break;
+ case ASAP_1_0.ASSIMILATE_CMD:
+ Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
+ "ASAPPDUExecutor call handleASAPAssimilate");
+ engineSetting.engine.handleASAPAssimilate(
+ (ASAP_AssimilationPDU_1_0) this.asapPDU,
+ this.protocol,
+ this.encounteredPeer, this.is, this.os,
+ this.connectionType,
+ this.engineSetting.listener);
+ break;
+
+ default:
+ Log.writeLogErr(this, ASAPSessionImpl.this.getLogParameter(),
+ "unknown ASAP command: " + asapPDU.getCommand());
+ }
+ }
+ catch(ASAPException asape) {
+ Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
+ "while processing PDU (go ahead): " + asape.getLocalizedMessage());
+ }
+ catch(IOException ioe) {
+ Log.writeLogErr(this, ASAPSessionImpl.this.getLogParameter(),
+ "IOException while processing ASAP PDU - close streams: " + ioe.getLocalizedMessage());
+ try {
+ os.close(); // more important to close than input stream - try first
+ is.close();
+ } catch (IOException ex) {
+ Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(), ex.getLocalizedMessage());
+ //ex.printStackTrace();
+ }
+ }
+ finally {
+ this.finish();
+ }
+ }
+ }
+
+ /**
+ * Waits for one PDU and goes away if read.
+ */
+ private class ASAPPDUReader extends Thread {
+ private final ASAP_1_0 protocol;
+ private final InputStream is;
+ private final ThreadFinishedListener pduReaderListener;
+ private ASAP_PDU_1_0 asapPDU = null;
+ private IOException ioException = null;
+ private ASAPException asapException = null;
+
+ ASAPPDUReader(ASAP_1_0 protocol, InputStream is, ThreadFinishedListener listener) {
+ this.protocol = protocol;
+ this.is = is;
+ this.pduReaderListener = listener;
+ }
+
+ IOException getIoException() {
+ return this.ioException;
+ }
+
+ ASAPException getAsapException() {
+ return this.asapException;
+ }
+
+ ASAP_PDU_1_0 getASAPPDU() {
+ return this.asapPDU;
+ }
+
+ public void run() {
+ try {
+ //boolean dropped = false;
+ //do {
+ //if(dropped) Log.writeLog(this, "dropped pdu: no sufficient encryption");
+ this.asapPDU = protocol.readPDU(is);
+ //dropped = true;
+ //} // refuse lesser security settings and read next pdu
+ //while((encrypt && !this.asapPDU.encrypted()) || (sign && !this.asapPDU.verified()));
+ } catch (IOException e) {
+ this.ioException = e;
+ Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
+ "IOException when reading from stream");
+ } catch (ASAPException e) {
+ Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
+ "ASAPException when reading from stream");
+ this.asapException = e;
+ }
+ finally {
+ if(this.pduReaderListener != null) {
+ this.pduReaderListener.finished(this);
+ }
+ }
+ }
+ }
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(this.asapInternalPeer.getOwner());
+ sb.append(" <--> ");
+ if(this.encounteredPeer == null) sb.append("");
+ else sb.append(this.encounteredPeer);
+ sb.append(" | type: ");
+ sb.append(this.connectionType);
+ sb.append(" | encrypted: ");
+ sb.append(this.encrypt);
+ sb.append(" | sign: ");
+ sb.append(this.sign);
+ return sb.toString();
+ }
+}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAP_1_0.java b/src/main/java/net/sharksystem/asap/protocol/ASAP_1_0.java
new file mode 100644
index 0000000..5fc4e86
--- /dev/null
+++ b/src/main/java/net/sharksystem/asap/protocol/ASAP_1_0.java
@@ -0,0 +1,229 @@
+package net.sharksystem.asap.protocol;
+
+import net.sharksystem.asap.ASAPException;
+import net.sharksystem.asap.ASAPHop;
+import net.sharksystem.asap.ASAPSecurityException;
+import net.sharksystem.asap.crypto.ASAPPoint2PointCryptoSettings;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Descriptions of ASAP protocol data units and some constants
+ */
+public interface ASAP_1_0 {
+ byte DEFAULT_INITIAL_TTL = 6; // a small world is assumed
+
+ int ENCRYPTED_MASK = 0x1; // 0001
+ byte ENCRYPTED_CMD = 1;
+
+ int CMD_MASK = 0x6; // 0110 - first bit tells if encrypted or not
+ byte INTEREST_CMD = 0;
+ byte ASSIMILATE_CMD = 2;
+
+ String ANY_FORMAT = "ASAP_ANY_FORMAT";
+ String ASAP_MANAGEMENT_FORMAT = "asap/control";
+ int ERA_NOT_DEFINED = -1;
+
+ /*
+ OFFER: An peer (optional) in an range of era (optional) offers data for
+ an channel (optional) in a format (mandatory)
+ */
+
+ /**
+ * @param peer identifies a peer - can be null
+ * @param era - current era of this peer (range 0..2^8) (-1 indicates: no information about era to be transmitted)
+ * @param channel describes a channel (can be null)
+ * @param format describes format - used to describe an application that can deal with transmitted data format.
+ * @param os stream that PDU is to be sent
+ * @param signed message is signed
+ * @throws IOException exception during writing on stream
+ * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
+ */
+// void offer(CharSequence peer, CharSequence format, CharSequence channel, int era, OutputStream os, boolean signed)
+// throws IOException, ASAPException;
+
+ /**
+ * @param recipient identifies a peer - can be null
+ * @param channel describes a channel (can be null)
+ * @param format describes format - used to describe an application that can deal with transmitted data format.
+ * @param os stream that PDU is to be sent
+ * @param signed message is signed
+ * @throws IOException exception during writing on stream
+ * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
+ */
+// void offer(CharSequence recipient, CharSequence format, CharSequence channel, OutputStream os, boolean signed)
+// throws IOException, ASAPException;
+
+ /*
+ INTEREST: Sender declares an interest for data from a peer (optional) within a range of era (optional) of a
+ channel (optional) in a format (mandatory)
+ */
+
+ /**
+ * @param sender identifies sender - can be null
+ * @param recipient can be null - no restriction - any encountered peer will get it.
+ * @param eraFrom lower limit of era range (-1 means undefined)
+ * @param eraTo upper limit of era range (-1 means undefined)
+ * @param channel whished / required channel (can be null)
+ * @param format describes format - used to describe an application that can deal with transmitted data format.
+ * @param os stream that PDU is to be sent
+ * @param signed message is signed
+ * @throws IOException exception during writing on stream
+ * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
+ */
+ void interest(CharSequence sender, CharSequence recipient, CharSequence format,
+ CharSequence channel, int eraFrom, int eraTo,
+ OutputStream os, boolean signed) throws IOException, ASAPException;
+
+ void interest(CharSequence sender, CharSequence recipient, CharSequence format,
+ CharSequence channel, int eraFrom, int eraTo,
+ OutputStream os, ASAPPoint2PointCryptoSettings cryptoSettings) throws IOException, ASAPException;
+
+ void interest(CharSequence sender, CharSequence recipient, CharSequence format,
+ CharSequence channel, int eraFrom, int eraTo,
+ OutputStream os, ASAPPoint2PointCryptoSettings cryptoSettings,
+ boolean asapRoutingAllowed) throws IOException, ASAPException;
+
+ /**
+ * @param sender identifies sender - can be null
+ * @param recipient can be null - no restriction - any encountered peer will get it.
+ * @param channel whished / required channel (can be null)
+ * @param format describes format - used to describe an application that can deal with transmitted data format.
+ * @param os stream that PDU is to be sent
+ * @throws IOException exception during writing on stream
+ * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
+ */
+ void interest(CharSequence sender, CharSequence recipient, CharSequence format,
+ CharSequence channel, OutputStream os) throws IOException, ASAPException;
+
+ /**
+ * @param sender identifies sender - can be null
+ * @param recipient can be null - no restriction - any encountered peer will get it.
+ * @param eraFrom lower limit of era range (-1 means undefined)
+ * @param eraTo upper limit of era range (-1 means undefined)
+ * @param channel whished / required channel (can be null)
+ * @param format describes format - used to describe an application that can deal with transmitted data format.
+ * @param os stream that PDU is to be sent
+ * @param sign sign message when sending
+ * @param encrypted encrypt method - of possible
+ * @throws IOException
+ * @throws ASAPException
+ */
+ void interest(CharSequence sender, CharSequence recipient, CharSequence format,
+ CharSequence channel, int eraFrom, int eraTo,
+ OutputStream os, boolean sign, boolean encrypted)
+ throws IOException, ASAPException, ASAPSecurityException;
+
+ void interest(CharSequence sender, CharSequence recipient, CharSequence format,
+ CharSequence channel, int eraFrom, int eraTo,
+ OutputStream os, boolean sign, boolean encrypted,
+ boolean asapRoutingAllowed, Map encounterMap)
+ throws IOException, ASAPException, ASAPSecurityException;
+
+ /**
+ * @param sender identifies sender - can be null
+ * @param channel whished / required channel (can be null)
+ * @param format describes format - used to describe an application that can deal with transmitted data format.
+ * @param os stream that PDU is to be sent
+ * @param signed message is signed
+ * @throws IOException exception during writing on stream
+ * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
+ */
+ void interest(CharSequence sender, CharSequence format, CharSequence sourcePeer,
+ CharSequence channel, OutputStream os, boolean signed, boolean encrypted)
+ throws IOException, ASAPException;
+
+ /*
+ ASSIMILATE: Peer (optional) issues data (mandatory) to a channel (mandatory) in a format (mandatory) of a
+ era (optional)
+ */
+
+ /**
+ *
+ * @param sender sender (optional, can be null)
+ * @param recipient wished recipient (optional, can be null)
+ * @param channelUri mandatory
+ * @param format mandatory
+ * @param offsets applications will probably store a number of messages in a data block. This (optional) list
+ * of numbers represents the offset where a new app specific message begins.
+ * @param dataIS stream from which are read to be transmitted to recipient mandatory
+ * @param os stream that PDU is to be sent
+ * @param signed message is signed
+ * @throws IOException exception during writing on stream
+ * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
+ */
+ void assimilate(CharSequence sender, CharSequence recipient, CharSequence format, CharSequence channelUri, int era,
+ long length, List offsets, List