Commit 80948d67 authored by LIly's avatar LIly

merge

parents 9bb8f0d7 af1a78f6
......@@ -8,7 +8,6 @@
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/ebcagent" />
<option value="$PROJECT_DIR$/ebclibrary" />
<option value="$PROJECT_DIR$/ebcmessageapp" />
<option value="$PROJECT_DIR$/ebcutils" />
......
......@@ -40,14 +40,15 @@ import static org.mpisws.encounters.EncounterBasedCommunication.CHANGE_EPOCH_TIM
*/
public class SimulatorEncounterFormationCore implements Runnable {
private static final String TAG = SimulatorEncounterFormationCore.class.getSimpleName();
protected static final int NUM_SIMULATED_DEVICES = 10;
private static final int NUM_SIMULATED_EPOCHS = 30;
public static final int NUM_SIMULATED_DEVICES = 10;
public static final int NUM_SIMULATED_EPOCHS = 20;
protected static List<Identifier> mDHPubKeys = new ArrayList<>(NUM_SIMULATED_EPOCHS);
protected static List<Identifier> mDHNonces = new ArrayList<>(NUM_SIMULATED_EPOCHS);
protected static List<Identifier> mDHFullKeys = new ArrayList<>(NUM_SIMULATED_EPOCHS);
protected static List<Identifier> otherDHPubKeys = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static List<Identifier> otherDHNonces = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
public static List<Identifier> otherDHPubKeys = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
public static List<Identifier> otherDHNonces = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static List<Identifier> otherDHFullKeys = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
public static List<Identifier> mSharedSecrets = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static int CURRENT_EPOCH = 0;
protected static Identifier mDHPubKey;
......@@ -81,19 +82,15 @@ public class SimulatorEncounterFormationCore implements Runnable {
changeEpochTime = System.currentTimeMillis() + CHANGE_EPOCH_TIME;
encounterConfirmationAndEpochLinking = new SimulatorEncounterConfirmationAndEpochLinking(mService);
new EncounterEntriesBridge(mService).finalizeOldEncounters();
if (initializeSimulatedAdverts() == -1)
throw new IllegalStateException("No device listening to post link adverts");
initializeSimulatedAdverts();
}
private int initializeSimulatedAdverts() {
Socket clientSocket;
List<Pair<Identifier, Identifier>> topicsToCreate = new ArrayList<>();
private void initializeSimulatedAdverts() {
for (int i = 0; i < NUM_SIMULATED_EPOCHS*NUM_SIMULATED_DEVICES; i++) {
SDDR_Native.c_changeEpoch();
otherDHPubKeys.add(new Identifier(SDDR_Native.c_getAdvertDHPubKey()));
otherDHFullKeys.add(new Identifier(SDDR_Native.c_getAdvertDHKey()));
otherDHNonces.add(new Identifier(SDDR_Native.c_getMyAdvert()));
topicsToCreate.add(new ImmutablePair<>(otherDHNonces.get(i), otherDHPubKeys.get(i)));
}
for (int i = 0; i < NUM_SIMULATED_EPOCHS; i++) {
SDDR_Native.c_changeEpoch();
......@@ -106,36 +103,10 @@ public class SimulatorEncounterFormationCore implements Runnable {
otherDHFullKeys.get(j+(NUM_SIMULATED_DEVICES*i)).getBytes(),
mDHNonces.get(i).getBytes(),
mDHPubKeys.get(i).getBytes()));
topicsToCreate.add(new ImmutablePair<>(sharedSecret, sharedSecret));
mSharedSecrets.add(sharedSecret);
}
}
Thread thread = new Thread(() -> {
try {
//Replace below IP with the IP of that device in which server socket open.
//If you change port then change the port number in the server side code also.
Socket s = new Socket("xxx.xxx.xxx.xxx", 9002);
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(msg);
output.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
final String st = input.readLine();
output.close();
out.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
});
thread.start();
Log.d(TAG, "Creating " + topicsToCreate.size() + " topics");
ESClient.getInstance().createTopics(topicsToCreate);
// TODO do server stuff here
}
public void run() {
......
include ':ebclibrary', ':testapp', ':ebcagent', ':ebcutils', ':exampleapp', ':ebcmessageapp'
include ':ebclibrary', ':testapp', ':ebcutils', ':exampleapp', ':ebcmessageapp'
package org.mpisws.testapp;
import android.content.Context;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.util.Log;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.mSharedSecrets;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.otherDHNonces;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.otherDHPubKeys;
public class SimulationClient {
static private String TAG = SimulationClient.class.getSimpleName();
static private String mServiceName = "EbCSimulator";
static private String mServiceType = "_ebcsimulator._tcp";
private NsdManager.DiscoveryListener mDiscoveryListener;
private NsdManager mNsdManager;
private NsdManager.ResolveListener mResolveListener;
private NsdServiceInfo mService;
private InetAddress mHost;
private int mPort;
private Socket sock = null;
SimulationClient(Context context) {
mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
}
public void sendDataToSimulationServer() {
initializeDiscoveryListener();
initializeResolveListener();
mNsdManager.discoverServices(mServiceType, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}
public void initializeDiscoveryListener() {
// Instantiate a new DiscoveryListener
mDiscoveryListener = new NsdManager.DiscoveryListener() {
// Called as soon as service discovery begins.
@Override
public void onDiscoveryStarted(String regType) {
Log.d(TAG, "Service discovery started");
}
@Override
public void onServiceFound(NsdServiceInfo service) {
// A service was found! Do something with it.
Log.d(TAG, "Service discovery success" + service);
if (!service.getServiceType().equals(mServiceType)) {
// Service type is the string containing the protocol and
// transport layer for this service.
Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
} else if (service.getServiceName().contains("EbCSimulator")){
mNsdManager.resolveService(service, mResolveListener);
}
}
@Override
public void onServiceLost(NsdServiceInfo service) {
// When the network service is no longer available.
// Internal bookkeeping code goes here.
Log.e(TAG, "service lost" + service);
}
@Override
public void onDiscoveryStopped(String serviceType) {
Log.i(TAG, "Discovery stopped: " + serviceType);
}
@Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
@Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
};
}
public void initializeResolveListener() {
mResolveListener = new NsdManager.ResolveListener() {
@Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Called when the resolve fails. Use the error code to debug.
Log.e(TAG, "Resolve failed" + errorCode);
}
@Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.e(TAG, "Resolve Succeeded. " + serviceInfo);
if (serviceInfo.getServiceName().equals(mServiceName)) {
Log.d(TAG, "Same IP.");
return;
}
mService = serviceInfo;
mPort = mService.getPort();
mHost = mService.getHost();
mNsdManager.stopServiceDiscovery(mDiscoveryListener);
sendDHKeysOverSocket();
}
};
}
public void sendDHKeysOverSocket() {
new Thread(() -> {
try {
sock = new Socket(mHost, mPort);
if (sock == null) return;
String serializedSecrets;
String serializedNonces;
String serializedPubKeys;
// serialize
OutputStream os = sock.getOutputStream();
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(mSharedSecrets);
so.flush();
serializedSecrets = bo.toString();
so.writeObject(otherDHNonces);
so.flush();
serializedNonces = bo.toString();
so.writeObject(otherDHPubKeys);
so.flush();
serializedPubKeys = bo.toString();
} catch (Exception e) {
System.out.println(e);
return;
}
// write over socket
PrintWriter pw = new PrintWriter(os, true);
pw.println(serializedSecrets);
pw.println(serializedNonces);
pw.println(serializedPubKeys);
// wait for server to ack
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
Log.d(TAG, line);
}
in.close();
pw.close();
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
package org.mpisws.testapp;
import android.content.Context;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.os.Handler;
import android.util.Log;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.mpisws.embeddedsocial.ESClient;
import org.mpisws.embeddedsocial.ESMessage;
import org.mpisws.helpers.Identifier;
import org.mpisws.helpers.Utils;
import org.mpisws.messaging.EpochLinkMessage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import static org.mpisws.encounters.EncounterBasedCommunication.CHANGE_EPOCH_TIME;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.NUM_SIMULATED_DEVICES;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.NUM_SIMULATED_EPOCHS;
import static org.mpisws.helpers.Utils.SHA1;
public class SimulationServer {
private static final String TAG = SimulationServer.class.getSimpleName();
static private int port;
static private String mServiceName = "EbCSimulator";
static private String mServiceType = "_ebcsimulator._tcp";
private int currentEpoch = 0;
private ServerSocket mServerSocket;
private NsdManager.RegistrationListener mRegistrationListener;
private NsdManager mNsdManager;
private List<Identifier> nonces;
private List<Identifier> sharedSecrets;
private List<Identifier> pubKeys;
SimulationServer(Context context) {
mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
}
public void startServer() {
new Thread(() -> {
// Initialize a server socket on the next available port.
try {
mServerSocket = new ServerSocket(0);
// Store the chosen port.
port = mServerSocket.getLocalPort();
registerService(port);
Socket sock = mServerSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
List<String> lines = new ArrayList<>();
String line;
while ((line = in.readLine()) != null) {
lines.add(line);
}
PrintStream output = new PrintStream(sock.getOutputStream());
output.println("Finished");
Utils.myAssert(lines.size() == 3);
sharedSecrets = deserializeIDList(lines.get(0));
nonces = deserializeIDList(lines.get(1));
pubKeys = deserializeIDList(lines.get(2));
if (sharedSecrets == null || nonces == null) {
return;
}
output.close();
in.close();
sock.close();
processData();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}).start();
}
private void processData() {
// Create all topics you'll ever have to create
List<Pair<Identifier, Identifier>> topicsToCreate = new ArrayList<>();
for (int i=0; i < nonces.size(); i++) {
topicsToCreate.add(new ImmutablePair<>(nonces.get(i), pubKeys.get(i)));
}
for (Identifier ss : sharedSecrets) {
topicsToCreate.add(new ImmutablePair<>(ss, ss));
}
ESClient.getInstance().createTopics(topicsToCreate);
// Every "epoch" or so try to post link messages to the prior "epoch" ss for each "device"
// Let's try and post to the prior 3 epochs
new Handler().postDelayed(() -> {
int lowEpoch = currentEpoch > 3 ? currentEpoch - 3 : 0;
List<Identifier> sses = sharedSecrets.subList(lowEpoch*NUM_SIMULATED_DEVICES, currentEpoch*NUM_SIMULATED_DEVICES);
List<String> topicHandles = ESClient.getInstance().getTopicHandles(sses);
List<ESMessage> msgsToSend = new ArrayList<>();
for (int i = 0; i < NUM_SIMULATED_DEVICES; i++) {
for (int j = currentEpoch+1; j > lowEpoch+1; j--) {
int oldIndex = (j-1-lowEpoch)*NUM_SIMULATED_DEVICES + i;
int newIndex = (j-lowEpoch)*NUM_SIMULATED_DEVICES + i;
if (topicHandles.get(oldIndex) == null || topicHandles.get(oldIndex).compareTo("") == 0) {
continue;
}
EpochLinkMessage epochLinkMessage = new EpochLinkMessage.EpochLinkMessageBuilder()
.addOldNonce(nonces.get((lowEpoch*NUM_SIMULATED_DEVICES) + oldIndex).toString())
.addNewNonce(nonces.get((lowEpoch*NUM_SIMULATED_DEVICES) + newIndex).toString())
.build();
msgsToSend.add(new ESMessage(epochLinkMessage.toSendMessageText(sses.get(oldIndex).getBytes()),
new Identifier(SHA1(sharedSecrets.get(i).getBytes())).toString(),
topicHandles.get(oldIndex),
true, null, true, -1));
}
}
ESClient.getInstance().sendMsgs(msgsToSend);
currentEpoch++;
// heh hack
if (currentEpoch == NUM_SIMULATED_EPOCHS) currentEpoch--;
}, CHANGE_EPOCH_TIME);
}
private List<Identifier> deserializeIDList(String serializedObject) throws IOException, ClassNotFoundException {
byte b[] = serializedObject.getBytes();
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
List<Identifier> obj = (List<Identifier>) si.readObject();
return obj;
}
public void registerService(int port) {
// Create the NsdServiceInfo object, and populate it.
NsdServiceInfo serviceInfo = new NsdServiceInfo();
// The name is subject to change based on conflicts
// with other services advertised on the same network.
serviceInfo.setServiceName(mServiceName);
serviceInfo.setServiceType(mServiceType);
serviceInfo.setPort(port);
initializeRegistrationListener();
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
public void initializeRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
@Override
public void onServiceRegistered(NsdServiceInfo NsdServiceInfo) {
// Save the service name. Android may have changed it in order to
// resolve a conflict, so update the name you initially requested
// with the name Android actually used.
mServiceName = NsdServiceInfo.getServiceName();
Log.d(TAG, "Registration success " + mServiceName);
}
@Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.d(TAG, "Registration failed " + errorCode);
}
@Override
public void onServiceUnregistered(NsdServiceInfo arg0) {
// Service has been unregistered. This only happens when you call
// NsdManager.unregisterService() and pass in this listener.
}
@Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Unregistration failed. Put debugging code here to determine why.
}
};
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment