M1-nw-project/main.cpp

91 lines
2.1 KiB
C++
Raw Normal View History

2016-11-18 10:56:51 +01:00
/***************************************************************************
* By Théophile Bastian, 2017
* M1 Network course project at ENS Cachan, Juliusz Chroboczek.
* License: WTFPL v2 <http://www.wtfpl.net/>
**************************************************************************/
#include "data.h"
2016-11-20 00:16:13 +01:00
#include "protocol.h"
#include "nw_constants.h"
#include "neighbours.h"
2016-11-24 14:39:03 +01:00
#include "packetParser.h"
2016-11-24 15:26:42 +01:00
#include "configFile.h"
2016-11-26 16:20:20 +01:00
#include "dataStore.h"
2016-11-20 00:16:13 +01:00
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <unistd.h>
2016-11-26 19:17:56 +01:00
#include <signal.h>
bool terminate=false;
2016-11-20 00:16:13 +01:00
2016-11-24 15:26:42 +01:00
int main(int argc, char** argv) {
bool hasConfig = false;
char* configFilePath = nullptr;
if(argc > 1) {
hasConfig = true;
configFilePath = argv[1];
}
2016-11-20 00:16:13 +01:00
srand(time(NULL)+42);
2016-11-26 19:17:56 +01:00
signal(SIGINT, [](int) { terminate = true; });
2016-11-24 15:26:42 +01:00
ConfigFile cfg;
if(hasConfig) {
if(!cfg.read(configFilePath) || !cfg.write(configFilePath)) {
fprintf(stderr, "Could not read/write on '%s'.\n", configFilePath);
exit(1);
}
}
2016-11-20 00:16:13 +01:00
SockAddr addr;
memset(&addr, 0, sizeof(addr));
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(csts::DEFAULT_PORT);
2016-11-20 00:16:13 +01:00
2016-11-26 19:17:56 +01:00
fprintf(stderr, "[INFO] Starting with ID %lX\n", cfg.getSelfId());
2016-11-24 15:26:42 +01:00
Protocol proto(addr, cfg.getSelfId());
2016-11-26 16:20:20 +01:00
DataStore dataStore(&proto);
2016-11-26 19:17:56 +01:00
for(auto dat : cfg.getData()) {
Bytes pck;
pck << csts::TLV_DATA_TEXT << (u8)dat.second.size();
for(u8 chr : dat.second)
pck << chr;
dataStore.addData(pck, time(NULL), dat.first, true);
fprintf(stderr, "[INFO] Adding data `%s`\n", dat.second.c_str());
}
2016-11-26 16:20:20 +01:00
Neighbours neighboursManager(&proto, &dataStore);
2016-11-24 15:26:42 +01:00
for(const Neighbour& nei : cfg.getBootstrapNodes()) {
char addr[54];
inet_ntop(AF_INET6, &nei.addr.sin6_addr, addr, 54);
2016-11-26 19:17:56 +01:00
fprintf(stderr, "[INFO] Bootstrap neighbour: %lX [%s]:%hu\n",
nei.id, addr, ntohs(nei.addr.sin6_port));
2016-11-24 15:26:42 +01:00
neighboursManager.addPotentialNei(nei);
}
2016-11-26 16:20:20 +01:00
PacketParser pckParser(&neighboursManager, &proto, &dataStore);
2016-11-24 14:39:03 +01:00
2016-11-26 19:17:56 +01:00
while(!terminate) {
neighboursManager.fullUpdate();
2016-11-24 14:39:03 +01:00
while(proto.readyRead()) {
SockAddr fromAddr;
Bytes pck = proto.getPacket(&fromAddr);
2016-11-26 16:20:20 +01:00
pckParser.parse(pck, fromAddr);
2016-11-24 14:39:03 +01:00
}
2016-11-26 16:20:20 +01:00
dataStore.update();
sleep(1);
}
2016-11-20 00:16:13 +01:00
return 0;
2016-11-18 10:56:51 +01:00
}