Commit 5ef04e05 authored by Lily Tsai's avatar Lily Tsai

remove redundant nsd server and client

parent 182ef779
...@@ -23,9 +23,7 @@ import org.mpisws.encounters.EncounterBasedCommunication; ...@@ -23,9 +23,7 @@ import org.mpisws.encounters.EncounterBasedCommunication;
import org.mpisws.messaging.ReceivedMessageWrapper; import org.mpisws.messaging.ReceivedMessageWrapper;
import org.mpisws.testapp.googleauth.GoogleNativeAuthenticator; import org.mpisws.testapp.googleauth.GoogleNativeAuthenticator;
import org.mpisws.testapp.googleauth.GoogleToken; import org.mpisws.testapp.googleauth.GoogleToken;
import org.mpisws.testapp.simulator.SimulationClient;
import org.mpisws.testapp.simulator.SimulationClientBT; import org.mpisws.testapp.simulator.SimulationClientBT;
import org.mpisws.testapp.simulator.SimulationServer;
import org.mpisws.testapp.simulator.SimulationServerBT; import org.mpisws.testapp.simulator.SimulationServerBT;
import java.util.List; import java.util.List;
......
package org.mpisws.testapp.simulator;
import android.content.Context;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.util.Log;
import org.mpisws.encounters.encounterformation.SDDR_Native;
import org.mpisws.helpers.Identifier;
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 java.util.ArrayList;
import java.util.List;
public class SimulationClient {
static private String TAG = SimulationClient.class.getSimpleName();
static private SimulatorEncounterFormationCore core;
protected static final int NUM_SIMULATED_DEVICES = 10;
protected static final int NUM_SIMULATED_EPOCHS = 10;
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);
protected static List<Identifier> otherDHFullKeys = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static List<Identifier> mSharedSecrets = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static int CURRENT_EPOCH = 0;
static protected String mServiceName = "EbCSimulation";
static protected String mServiceType = "_http._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;
public SimulationClient(Context context) {
mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
initializeSimulatedAdverts();
initializeDiscoveryListener();
initializeResolveListener();
core = new SimulatorEncounterFormationCore(context);
}
public void sendDataToSimulationServerAndStartCore() {
mNsdManager.discoverServices(mServiceType, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}
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()));
}
for (int i = 0; i < NUM_SIMULATED_EPOCHS; i++) {
SDDR_Native.c_changeEpoch();
mDHPubKeys.add(new Identifier(SDDR_Native.c_getAdvertDHPubKey()));
mDHFullKeys.add(new Identifier(SDDR_Native.c_getAdvertDHKey()));
mDHNonces.add(new Identifier(SDDR_Native.c_getMyAdvert()));
for (int j = 0; j < NUM_SIMULATED_DEVICES; j++) {
Identifier sharedSecret = new Identifier(SDDR_Native.c_computeSecretKeyWithSHA(
otherDHFullKeys.get(j+(NUM_SIMULATED_DEVICES*i)).getBytes(),
mDHNonces.get(i).getBytes(),
mDHPubKeys.get(i).getBytes()));
mSharedSecrets.add(sharedSecret);
}
}
}
private 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(mServiceName)){
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);
}
};
}
private 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();
}
};
}
private 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, "Got response: " + line);
}
in.close();
pw.close();
sock.close();
// run the simulator core
Log.d(TAG, "Running simulator core!");
core.run();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
...@@ -13,26 +13,14 @@ import org.mpisws.encounters.encounterformation.SDDR_Native; ...@@ -13,26 +13,14 @@ import org.mpisws.encounters.encounterformation.SDDR_Native;
import org.mpisws.helpers.Identifier; import org.mpisws.helpers.Identifier;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintWriter; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import static org.mpisws.testapp.simulator.SimulationClient.NUM_SIMULATED_DEVICES;
import static org.mpisws.testapp.simulator.SimulationClient.NUM_SIMULATED_EPOCHS;
import static org.mpisws.testapp.simulator.SimulationClient.mDHFullKeys;
import static org.mpisws.testapp.simulator.SimulationClient.mDHNonces;
import static org.mpisws.testapp.simulator.SimulationClient.mDHPubKeys;
import static org.mpisws.testapp.simulator.SimulationClient.mSharedSecrets;
import static org.mpisws.testapp.simulator.SimulationClient.otherDHFullKeys;
import static org.mpisws.testapp.simulator.SimulationClient.otherDHNonces;
import static org.mpisws.testapp.simulator.SimulationClient.otherDHPubKeys;
/** /**
* This class does all the work for setting up and managing Bluetooth * This class does all the work for setting up and managing Bluetooth
* connections with other devices. It has a thread that listens for * connections with other devices. It has a thread that listens for
...@@ -46,6 +34,17 @@ public class SimulationClientBT { ...@@ -46,6 +34,17 @@ public class SimulationClientBT {
private final BluetoothAdapter mAdapter; private final BluetoothAdapter mAdapter;
static private SimulatorEncounterFormationCore core; static private SimulatorEncounterFormationCore core;
protected static final int NUM_SIMULATED_DEVICES = 10;
protected static final int NUM_SIMULATED_EPOCHS = 10;
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);
protected static List<Identifier> otherDHFullKeys = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static List<Identifier> mSharedSecrets = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static int CURRENT_EPOCH = 0;
public SimulationClientBT(Context context) { public SimulationClientBT(Context context) {
this.context = context; this.context = context;
mAdapter = BluetoothAdapter.getDefaultAdapter(); mAdapter = BluetoothAdapter.getDefaultAdapter();
...@@ -117,12 +116,6 @@ public class SimulationClientBT { ...@@ -117,12 +116,6 @@ public class SimulationClientBT {
private void sendDHKeysOverSocket(BluetoothSocket sock) { private void sendDHKeysOverSocket(BluetoothSocket sock) {
try { try {
if (sock == null) return; if (sock == null) return;
String serializedSecrets;
String serializedNonces;
String serializedPubKeys;
// serialize
OutputStream os = sock.getOutputStream(); OutputStream os = sock.getOutputStream();
ObjectOutputStream out = new ObjectOutputStream(os); ObjectOutputStream out = new ObjectOutputStream(os);
out.writeObject(mSharedSecrets); out.writeObject(mSharedSecrets);
......
package org.mpisws.testapp.simulator;
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.helpers.Utils.SHA1;
import static org.mpisws.testapp.simulator.SimulationClient.NUM_SIMULATED_DEVICES;
import static org.mpisws.testapp.simulator.SimulationClient.NUM_SIMULATED_EPOCHS;
import static org.mpisws.testapp.simulator.SimulationClient.mServiceName;
import static org.mpisws.testapp.simulator.SimulationClient.mServiceType;
public class SimulationServer {
private static final String TAG = SimulationServer.class.getSimpleName();
static private int port;
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;
public 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);
} catch (IOException e) {
e.printStackTrace();
}
// Store the chosen port.
port = mServerSocket.getLocalPort();
Log.d(TAG, "Simulation Server opened on port " + port);
registerService(port);
}).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));
}
Log.d(TAG, "Creating topics: " + topicsToCreate.size());
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;
}
private 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();
Log.d(TAG, "Registering service");
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
private void initializeRegistrationListener() {
Log.d(TAG, "Initializing registration listener");
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);
try {
Socket sock = mServerSocket.accept();
Log.d(TAG, "Accepted sock connection");
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 || pubKeys == null) {
return;
}
output.close();
in.close();
sock.close();
mNsdManager.unregisterService(this);
processData();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
@Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.d(TAG, "Registration failed " + errorCode);
}
@Override
public void onServiceUnregistered(NsdServiceInfo arg0) {
Log.d(TAG, "Registration listener unregistered");
// 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) {
Log.d(TAG, "UnRegistration listener failed " + errorCode);
}
};
}
}
...@@ -14,17 +14,10 @@ import org.apache.commons.lang3.tuple.Pair; ...@@ -14,17 +14,10 @@ import org.apache.commons.lang3.tuple.Pair;
import org.mpisws.embeddedsocial.ESClient; import org.mpisws.embeddedsocial.ESClient;
import org.mpisws.embeddedsocial.ESMessage; import org.mpisws.embeddedsocial.ESMessage;
import org.mpisws.helpers.Identifier; import org.mpisws.helpers.Identifier;
import org.mpisws.helpers.Utils;
import org.mpisws.messaging.EpochLinkMessage; import org.mpisws.messaging.EpochLinkMessage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
...@@ -32,8 +25,8 @@ import java.util.UUID; ...@@ -32,8 +25,8 @@ import java.util.UUID;
import static org.mpisws.encounters.EncounterBasedCommunication.CHANGE_EPOCH_TIME; import static org.mpisws.encounters.EncounterBasedCommunication.CHANGE_EPOCH_TIME;
import static org.mpisws.helpers.Utils.SHA1; import static org.mpisws.helpers.Utils.SHA1;
import static org.mpisws.testapp.simulator.SimulationClient.NUM_SIMULATED_DEVICES; import static org.mpisws.testapp.simulator.SimulationClientBT.NUM_SIMULATED_DEVICES;
import static org.mpisws.testapp.simulator.SimulationClient.NUM_SIMULATED_EPOCHS; import static org.mpisws.testapp.simulator.SimulationClientBT.NUM_SIMULATED_EPOCHS;
/** /**
* This class does all the work for setting up and managing Bluetooth * This class does all the work for setting up and managing Bluetooth
......
...@@ -18,11 +18,11 @@ import java.util.HashMap; ...@@ -18,11 +18,11 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.mpisws.encounters.EncounterBasedCommunication.CHANGE_EPOCH_TIME; import static org.mpisws.encounters.EncounterBasedCommunication.CHANGE_EPOCH_TIME;
import static org.mpisws.testapp.simulator.SimulationClient.NUM_SIMULATED_EPOCHS; import static org.mpisws.testapp.simulator.SimulationClientBT.NUM_SIMULATED_EPOCHS;
import static org.mpisws.testapp.simulator.SimulationClient.CURRENT_EPOCH; import static org.mpisws.testapp.simulator.SimulationClientBT.CURRENT_EPOCH;
import static org.mpisws.testapp.simulator.SimulationClient.mDHFullKeys; import static org.mpisws.testapp.simulator.SimulationClientBT.mDHFullKeys;
import static org.mpisws.testapp.simulator.SimulationClient.mDHNonces; import static org.mpisws.testapp.simulator.SimulationClientBT.mDHNonces;
import static org.mpisws.testapp.simulator.SimulationClient.mDHPubKeys; import static org.mpisws.testapp.simulator.SimulationClientBT.mDHPubKeys;
/** /**
* SDDR_Core implements the core functionality of the SDDR protocol. It is started and called by the * SDDR_Core implements the core functionality of the SDDR protocol. It is started and called by the
......
...@@ -46,9 +46,9 @@ import java.util.List; ...@@ -46,9 +46,9 @@ import java.util.List;
import static android.bluetooth.le.ScanSettings.SCAN_MODE_LOW_POWER; import static android.bluetooth.le.ScanSettings.SCAN_MODE_LOW_POWER;
import static org.mpisws.encounters.EncounterBasedCommunication.SCAN_BATCH_INTERVAL; import static org.mpisws.encounters.EncounterBasedCommunication.SCAN_BATCH_INTERVAL;
import static org.mpisws.testapp.simulator.SimulationClient.CURRENT_EPOCH;