This commit is contained in:
j3d1 2016-02-25 19:46:35 +01:00
parent f15abc71be
commit 1f3730ac87
26 changed files with 880 additions and 844 deletions

View file

@ -10,31 +10,32 @@
#include "Constant.h" #include "Constant.h"
std::string File::read() { std::string File::read() {
if (!fs::exists(home)) { if (!fs::exists(home)) {
fs::create_directory(home); fs::create_directory(home);
} }
fs::ifstream in(((options.file=="")?home / DEFAULT_FILE:options.file), std::ios::in | std::ios::binary); fs::ifstream in(((options.file == "") ? home / DEFAULT_FILE : options.file),
if (in) { std::ios::in | std::ios::binary);
std::string contents; if (in) {
in.seekg(0, std::ios::end); std::string contents;
contents.resize(in.tellg()); in.seekg(0, std::ios::end);
in.seekg(0, std::ios::beg); contents.resize(in.tellg());
in.read(&contents[0], contents.size()); in.seekg(0, std::ios::beg);
in.close(); in.read(&contents[0], contents.size());
return (contents); in.close();
} return (contents);
return ""; }
return "";
} }
int File::write(std::string content) { int File::write(std::string content) {
if (!fs::exists(home)) { if (!fs::exists(home)) {
fs::create_directory(home); fs::create_directory(home);
} }
fs::path p = (options.file=="")?home / DEFAULT_FILE:options.file; fs::path p = (options.file == "") ? home / DEFAULT_FILE : options.file;
fs::ofstream file(p); fs::ofstream file(p);
file << content<<"\n"; file << content << "\n";
file.close(); file.close();
return 0; return 0;
} }

View file

@ -17,14 +17,14 @@ namespace fs = boost::filesystem;
#define DEFAULT_FILE "config.json" #define DEFAULT_FILE "config.json"
class File { class File {
public: public:
File() { File() {
home = fs::path(getenv("HOME")) / ".smrtlink"; home = fs::path(getenv("HOME")) / ".smrtlink";
} }
std::string read(); std::string read();
int write(std::string); int write(std::string);
private: private:
fs::path home; fs::path home;
}; };
#endif /* FILE_H_ */ #endif /* FILE_H_ */

View file

@ -30,7 +30,8 @@ Filter Filter::tokenid(short i) {
} }
bool Filter::pass(const Packet p) const { bool Filter::pass(const Packet p) const {
macAddr none { 0, 0, 0, 0, 0, 0 }; macAddr none {
0, 0, 0, 0, 0, 0 };
if (this->oc != Packet::NONE && this->oc != p.getOpCode()) if (this->oc != Packet::NONE && this->oc != p.getOpCode())
return false; return false;
if (this->switchMac != none && this->switchMac != p.getSwitchMac()) if (this->switchMac != none && this->switchMac != p.getSwitchMac())
@ -44,7 +45,7 @@ bool Filter::pass(const Packet p) const {
bool Filter::operator<(const Filter f) const { bool Filter::operator<(const Filter f) const {
if (this->oc != f.oc) if (this->oc != f.oc)
return this->oc > f.oc; return this->oc > f.oc;
if (this->switchMac != f.switchMac) if (this->switchMac != f.switchMac)
return this->switchMac > f.switchMac; return this->switchMac > f.switchMac;
if (this->tokenId != f.tokenId) if (this->tokenId != f.tokenId)

View file

@ -11,20 +11,21 @@
#include "Packet.h" #include "Packet.h"
class Filter { class Filter {
public: public:
Filter(); Filter();
Filter(Packet::OpCode); Filter(Packet::OpCode);
Filter(macAddr); Filter(macAddr);
Filter opcode(Packet::OpCode); Filter opcode(Packet::OpCode);
Filter mac(macAddr); Filter mac(macAddr);
Filter tokenid(short); Filter tokenid(short);
bool pass(const Packet) const; bool pass(const Packet) const;
bool operator<(const Filter) const; bool operator<(const Filter) const;
private: private:
Packet::OpCode oc = Packet::NONE; Packet::OpCode oc = Packet::NONE;
macAddr switchMac = { 0, 0, 0, 0, 0, 0 }; macAddr switchMac = {
short tokenId = -1; 0, 0, 0, 0, 0, 0 };
short fragmentOffset = -1; short tokenId = -1;
short fragmentOffset = -1;
}; };
#endif /* FILTER_H_ */ #endif /* FILTER_H_ */

View file

@ -26,77 +26,79 @@
#include "Types.h" #include "Types.h"
macAddr Host::getMac() { macAddr Host::getMac() {
int s; int s;
struct ifreq buffer; struct ifreq buffer;
macAddr data { 0, 0, 0, 0, 0, 0 }; macAddr data {
if (options.interface != "") { 0, 0, 0, 0, 0, 0 };
s = socket(PF_INET, SOCK_DGRAM, 0); if (options.interface != "") {
memset(&buffer, 0x00, sizeof(buffer)); s = socket(PF_INET, SOCK_DGRAM, 0);
strcpy(buffer.ifr_name, options.interface.c_str()); memset(&buffer, 0x00, sizeof(buffer));
ioctl(s, SIOCGIFHWADDR, &buffer); strcpy(buffer.ifr_name, options.interface.c_str());
close(s); ioctl(s, SIOCGIFHWADDR, &buffer);
memcpy(&data[0], &buffer.ifr_hwaddr.sa_data[0], 6); close(s);
} memcpy(&data[0], &buffer.ifr_hwaddr.sa_data[0], 6);
return data; }
return data;
} }
ipAddr Host::getIp() { ipAddr Host::getIp() {
struct ifaddrs *ifaddr, *ifa; struct ifaddrs *ifaddr, *ifa;
int n; int n;
ipAddr data { 0, 0, 0, 0 }; ipAddr data {
if (getifaddrs(&ifaddr) == -1) { 0, 0, 0, 0 };
perror("getifaddrs"); if (getifaddrs(&ifaddr) == -1) {
exit(EXIT_FAILURE); perror("getifaddrs");
} exit(EXIT_FAILURE);
for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) { }
if (ifa->ifa_addr == NULL) for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
continue; if (ifa->ifa_addr == NULL)
if (ifa->ifa_addr->sa_family == AF_INET) continue;
if (options.interface.compare(ifa->ifa_name) == 0) { if (ifa->ifa_addr->sa_family == AF_INET)
memcpy(&data[0], &ifa->ifa_addr->sa_data[2], 4); if (options.interface.compare(ifa->ifa_name) == 0) {
return data; memcpy(&data[0], &ifa->ifa_addr->sa_data[2], 4);
} return data;
} }
/* }
for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) { /*
if (ifa->ifa_addr == NULL) for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
continue; if (ifa->ifa_addr == NULL)
if (ifa->ifa_addr->sa_family == AF_INET) continue;
if (getIface().compare(ifa->ifa_name) == 0) { if (ifa->ifa_addr->sa_family == AF_INET)
memcpy(&data[0], &ifa->ifa_addr->sa_data[2], 4); if (getIface().compare(ifa->ifa_name) == 0) {
return data; memcpy(&data[0], &ifa->ifa_addr->sa_data[2], 4);
} return data;
} }
*/ }
freeifaddrs(ifaddr); */
return data; freeifaddrs(ifaddr);
return data;
} }
std::string Host::getIface() { std::string Host::getIface() {
std::string defaultInterface; std::string defaultInterface;
std::ifstream routeFile("/proc/net/route", std::ios_base::in); std::ifstream routeFile("/proc/net/route", std::ios_base::in);
if (!routeFile.good()) if (!routeFile.good())
return ""; return "";
std::string line; std::string line;
std::vector<std::string> tokens; std::vector<std::string> tokens;
if (std::getline(routeFile, line)) if (std::getline(routeFile, line))
while (std::getline(routeFile, line)) { while (std::getline(routeFile, line)) {
std::istringstream stream(line); std::istringstream stream(line);
std::string delimiter = "\t"; std::string delimiter = "\t";
size_t pos = 0; size_t pos = 0;
std::string token; std::string token;
while ((pos = line.find(delimiter)) != std::string::npos) { while ((pos = line.find(delimiter)) != std::string::npos) {
token = line.substr(0, pos); token = line.substr(0, pos);
tokens.push_back(token); tokens.push_back(token);
line.erase(0, pos + delimiter.length()); line.erase(0, pos + delimiter.length());
} }
if ((tokens.size() >= 2) if ((tokens.size() >= 2)
&& (tokens[1] == std::string("00000000"))) { && (tokens[1] == std::string("00000000"))) {
defaultInterface = tokens[0]; defaultInterface = tokens[0];
break; break;
} }
tokens.clear(); tokens.clear();
} }
routeFile.close(); routeFile.close();
return defaultInterface; return defaultInterface;
} }

View file

@ -11,11 +11,12 @@
#include "Types.h" #include "Types.h"
class Host { class Host {
public: public:
Host(){}; Host() {
macAddr getMac(); }
ipAddr getIp(); macAddr getMac();
std::string getIface(); ipAddr getIp();
std::string getIface();
}; };
#endif /* HOST_H_ */ #endif /* HOST_H_ */

View file

@ -9,13 +9,13 @@
#define INTERACTIVE_H_ #define INTERACTIVE_H_
class Interactive { class Interactive {
public: public:
Interactive() { Interactive() {
} }
virtual ~Interactive() { virtual ~Interactive() {
} }
int loop(); int loop();
int single(std::vector<std::string> v); int single(std::vector<std::string> v);
}; };
#endif /* INTERACTIVE_H_ */ #endif /* INTERACTIVE_H_ */

View file

@ -150,42 +150,43 @@ void Packet::setTokenId(short tokenId) {
std::string Packet::opCodeToString() { std::string Packet::opCodeToString() {
switch (opCode) { switch (opCode) {
case DISCOVERY: case DISCOVERY:
return "DISCOVERY"; return "DISCOVERY";
case GET: case GET:
return "GET"; return "GET";
case SET: case SET:
return "SET"; return "SET";
case CONFIRM: case CONFIRM:
return "CONFIRM"; return "CONFIRM";
case REPLY: case REPLY:
return "REPLY"; return "REPLY";
default: default:
return "NONE"; return "NONE";
} }
return "NONE"; return "NONE";
} }
void Packet::encode(bytes &data) { void Packet::encode(bytes &data) {
int len = data.size(); int len = data.size();
bytes key = { 191, 155, 227, 202, 99, 162, 79, 104, 49, 18, 190, 164, 30, bytes key = {
76, 189, 131, 23, 52, 86, 106, 207, 125, 126, 169, 196, 28, 172, 58, 191, 155, 227, 202, 99, 162, 79, 104, 49, 18, 190, 164, 30, 76, 189,
188, 132, 160, 3, 36, 120, 144, 168, 12, 231, 116, 44, 41, 97, 108, 131, 23, 52, 86, 106, 207, 125, 126, 169, 196, 28, 172, 58, 188,
213, 42, 198, 32, 148, 218, 107, 247, 112, 204, 14, 66, 68, 91, 224, 132, 160, 3, 36, 120, 144, 168, 12, 231, 116, 44, 41, 97, 108, 213,
206, 235, 33, 130, 203, 178, 1, 134, 199, 78, 249, 123, 7, 145, 73, 42, 198, 32, 148, 218, 107, 247, 112, 204, 14, 66, 68, 91, 224, 206,
208, 209, 100, 74, 115, 72, 118, 8, 22, 243, 147, 64, 96, 5, 87, 60, 235, 33, 130, 203, 178, 1, 134, 199, 78, 249, 123, 7, 145, 73, 208,
113, 233, 152, 31, 219, 143, 174, 232, 153, 245, 158, 254, 70, 170, 209, 100, 74, 115, 72, 118, 8, 22, 243, 147, 64, 96, 5, 87, 60, 113,
75, 77, 215, 211, 59, 71, 133, 214, 157, 151, 6, 46, 81, 94, 136, 233, 152, 31, 219, 143, 174, 232, 153, 245, 158, 254, 70, 170, 75,
166, 210, 4, 43, 241, 29, 223, 176, 67, 63, 186, 137, 129, 40, 248, 77, 215, 211, 59, 71, 133, 214, 157, 151, 6, 46, 81, 94, 136, 166,
255, 55, 15, 62, 183, 222, 105, 236, 197, 127, 54, 179, 194, 229, 210, 4, 43, 241, 29, 223, 176, 67, 63, 186, 137, 129, 40, 248, 255,
185, 37, 90, 237, 184, 25, 156, 173, 26, 187, 220, 2, 225, 0, 240, 55, 15, 62, 183, 222, 105, 236, 197, 127, 54, 179, 194, 229, 185,
50, 251, 212, 253, 167, 17, 193, 205, 177, 21, 181, 246, 82, 226, 37, 90, 237, 184, 25, 156, 173, 26, 187, 220, 2, 225, 0, 240, 50,
38, 101, 163, 182, 242, 92, 20, 11, 95, 13, 230, 16, 121, 124, 109, 251, 212, 253, 167, 17, 193, 205, 177, 21, 181, 246, 82, 226, 38,
195, 117, 39, 98, 239, 84, 56, 139, 161, 47, 201, 51, 135, 250, 10, 101, 163, 182, 242, 92, 20, 11, 95, 13, 230, 16, 121, 124, 109, 195,
19, 150, 45, 111, 27, 24, 142, 80, 85, 83, 234, 138, 216, 57, 93, 117, 39, 98, 239, 84, 56, 139, 161, 47, 201, 51, 135, 250, 10, 19,
65, 154, 141, 122, 34, 140, 128, 238, 88, 89, 9, 146, 171, 149, 53, 150, 45, 111, 27, 24, 142, 80, 85, 83, 234, 138, 216, 57, 93, 65,
102, 61, 114, 69, 217, 175, 103, 228, 35, 180, 252, 200, 192, 165, 154, 141, 122, 34, 140, 128, 238, 88, 89, 9, 146, 171, 149, 53, 102,
159, 221, 244, 110, 119, 48 }; 61, 114, 69, 217, 175, 103, 228, 35, 180, 252, 200, 192, 165, 159,
221, 244, 110, 119, 48 };
bytes s = key; bytes s = key;
int i, j = 0; int i, j = 0;
for (int k = 0; k < len; k++) { for (int k = 0; k < len; k++) {
@ -199,7 +200,8 @@ void Packet::encode(bytes &data) {
void Packet::push(bytes &arr, int &index, byte data) { void Packet::push(bytes &arr, int &index, byte data) {
if (arr.size() > (unsigned) index) { if (arr.size() > (unsigned) index) {
arr[index++] = data; arr[index++] = data;
} else { }
else {
arr.push_back(data); arr.push_back(data);
index++; index++;
} }

View file

@ -16,65 +16,68 @@
static short sequenceId = 0; static short sequenceId = 0;
class Packet { class Packet {
public: public:
enum OpCode { enum OpCode {
DISCOVERY, GET, REPLY, SET, CONFIRM, NONE DISCOVERY, GET, REPLY, SET, CONFIRM, NONE
}; };
Packet(OpCode); Packet(OpCode);
static void encode(bytes&); static void encode(bytes&);
bytes getBytes(); bytes getBytes();
void parse(bytes); void parse(bytes);
void printHeader(); void printHeader();
std::string opCodeToString(); std::string opCodeToString();
short getLength() const; short getLength() const;
int getCheckSum() const; int getCheckSum() const;
int getErrorCode() const; int getErrorCode() const;
short getSequenceId() const; short getSequenceId() const;
macAddr getSwitchMac() const; macAddr getSwitchMac() const;
const bytes& getBody() const; const bytes& getBody() const;
const bytes& getHead() const; const bytes& getHead() const;
const datasets& getPayload() const; const datasets& getPayload() const;
void setBody(bytes); void setBody(bytes);
void setHostMac(macAddr); void setHostMac(macAddr);
void setSwitchMac(macAddr); void setSwitchMac(macAddr);
void setCheckSum(int); void setCheckSum(int);
void setSequenceId(short); void setSequenceId(short);
void setPayload(datasets payload); void setPayload(datasets payload);
short getTokenId() const; short getTokenId() const;
void setTokenId(short tokenId = 0); void setTokenId(short tokenId = 0);
byte getOpCode() const; byte getOpCode() const;
void setOpCode(byte opCode); void setOpCode(byte opCode);
private: private:
bytes head = bytes(32); bytes head = bytes(32);
bytes body = bytes(0); bytes body = bytes(0);
datasets payload; datasets payload;
byte version = 1; byte version = 1;
byte opCode; byte opCode;
macAddr switchMac { { 0, 0, 0, 0, 0, 0 } }; macAddr switchMac {
macAddr hostMac { { 0, 0, 0, 0, 0, 0 } }; { 0, 0, 0, 0, 0, 0 } };
macAddr broadcastMac { { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } }; macAddr hostMac {
short tokenId = 0; { 0, 0, 0, 0, 0, 0 } };
short fragmentOffset = 0; macAddr broadcastMac {
int errorCode = 0; { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } };
int checkSum = 0; short tokenId = 0;
short flag = 0; short fragmentOffset = 0;
void buildHead(); int errorCode = 0;
void buildBody(); int checkSum = 0;
void push(bytes&, int&, short); short flag = 0;
void push(bytes&, int&, int); void buildHead();
void push(bytes&, int&, byte); void buildBody();
void push(bytes&, int&, bytes); void push(bytes&, int&, short);
void push(bytes&, int&, ipAddr); void push(bytes&, int&, int);
void push(bytes&, int&, macAddr); void push(bytes&, int&, byte);
void push(bytes&, int&, dataset); void push(bytes&, int&, bytes);
void pull(bytes&, int&, short &); void push(bytes&, int&, ipAddr);
void pull(bytes&, int&, int&); void push(bytes&, int&, macAddr);
void pull(bytes&, int&, byte&); void push(bytes&, int&, dataset);
void pull(bytes&, int&, bytes&, unsigned); void pull(bytes&, int&, short &);
void pull(bytes&, int&, ipAddr&); void pull(bytes&, int&, int&);
void pull(bytes&, int&, macAddr&); void pull(bytes&, int&, byte&);
void pull(bytes&, int&, dataset&); void pull(bytes&, int&, bytes&, unsigned);
void pull(bytes&, int&, ipAddr&);
void pull(bytes&, int&, macAddr&);
void pull(bytes&, int&, dataset&);
}; };
#endif /* PACKET_H_ */ #endif /* PACKET_H_ */

View file

@ -35,87 +35,91 @@ int Program::run(vector<string> arg) {
io_service->reset(); io_service->reset();
sock->clear(); sock->clear();
switch (caseArg(cmd.c_str())) { switch (caseArg(cmd.c_str())) {
case caseArg("reboot"): case caseArg("reboot"):
if (reboot()) if (reboot())
return 1;
break;
case caseArg("reset"):
if (!reset())
return 0;
break;
case caseArg("save"):
if (save())
return 1;
break;
case caseArg("restore"):
if (restore())
return 1;
break;
case caseArg("flash"):
if (flash())
return 1;
break;
case caseArg("list"):
if (list())
return 1;
break;
case caseArg("sniff"):
if (sniff())
return 1;
break;
case caseArg("encode"):
if (optind < arg.size()) {
std::string s(arg[optind]);
optind++;
if (!encode(s))
return 1; return 1;
} else {
fprintf(stderr, "Argument expected after encode\n");
return 1;
}
break; break;
case caseArg("set"): case caseArg("reset"):
while (optind < arg.size()) { if (!reset())
if (regex_match(arg[optind].c_str(), sm, return 0;
std::regex("^([a-z]+)=(.*)$"))) { break;
if (!lookup.exists(sm[1])) { case caseArg("save"):
cerr << "Unknown argument " << arg[optind] << endl; if (save())
return 1;
break;
case caseArg("restore"):
if (restore())
return 1;
break;
case caseArg("flash"):
if (flash())
return 1;
break;
case caseArg("list"):
if (list())
return 1;
break;
case caseArg("sniff"):
if (sniff())
return 1;
break;
case caseArg("encode"):
if (optind < arg.size()) {
std::string s(arg[optind]);
optind++;
if (!encode(s))
return 1; return 1;
} }
ll.insert(std::pair<std::string, std::string>(sm[1], sm[2])); else {
} else { fprintf(stderr, "Argument expected after encode\n");
cerr << "Invalid Syntax " << arg[optind] << endl;
return 1; return 1;
} }
optind++;
}
if (setProperty(ll))
return 1;
break; break;
case caseArg("get"): case caseArg("set"):
while (optind < arg.size()) { while (optind < arg.size()) {
if (regex_match(arg[optind].c_str(), sm, if (regex_match(arg[optind].c_str(), sm,
std::regex("^([a-z]+)$"))) { std::regex("^([a-z]+)=(.*)$"))) {
if (!lookup.exists(sm[1])) { if (!lookup.exists(sm[1])) {
cerr << "Unknown argument " << arg[optind] << endl; cerr << "Unknown argument " << arg[optind] << endl;
return 1;
}
ll.insert(
std::pair<std::string, std::string>(sm[1], sm[2]));
}
else {
cerr << "Invalid Syntax " << arg[optind] << endl;
return 1; return 1;
} }
vect.push_back(sm[1]); optind++;
} else {
cerr << "Invalid argument " << arg[optind] << endl;
return 1;
} }
optind++; if (setProperty(ll))
} return 1;
if (getProperty(vect))
return 1;
break; break;
default: case caseArg("get"):
printf("Unknown command: %s\n", cmd.c_str()); while (optind < arg.size()) {
return 1; if (regex_match(arg[optind].c_str(), sm,
std::regex("^([a-z]+)$"))) {
if (!lookup.exists(sm[1])) {
cerr << "Unknown argument " << arg[optind] << endl;
return 1;
}
vect.push_back(sm[1]);
}
else {
cerr << "Invalid argument " << arg[optind] << endl;
return 1;
}
optind++;
}
if (getProperty(vect))
return 1;
break;
default:
printf("Unknown command: %s\n", cmd.c_str());
return 1;
} }
io_service->run(); io_service->run();
return 0; return 0;
@ -125,7 +129,8 @@ int printHeader(Packet p) {
if (options.flags.HEADER) { if (options.flags.HEADER) {
if (options.flags.HEX) { if (options.flags.HEX) {
cout << "Received Header:\n\t" << p.getHead() << "\n"; cout << "Received Header:\n\t" << p.getHead() << "\n";
} else { }
else {
p.printHeader(); p.printHeader();
printf("\n"); printf("\n");
} }
@ -136,48 +141,53 @@ int printHeader(Packet p) {
int printPacket(Packet p) { int printPacket(Packet p) {
if (options.flags.HEX) { if (options.flags.HEX) {
cout << "Received Payload:\n\t" << p.getBody() << "\n"; cout << "Received Payload:\n\t" << p.getBody() << "\n";
} else { }
else {
for (dataset d : p.getPayload()) { for (dataset d : p.getPayload()) {
//auto lookup = (options.flags.REVERSE) ? snd_lookup : rcv_lookup; //auto lookup = (options.flags.REVERSE) ? snd_lookup : rcv_lookup;
if (lookup.exists(d.type)) { if (lookup.exists(d.type)) {
table::set s = lookup[d.type]; table::set s = lookup[d.type];
if (d.len > 0) { if (d.len > 0) {
switch (s.format) { switch (s.format) {
case table::STRING: case table::STRING:
cout << "+\t" << s.name << " = " << &d.value[0] << "\n"; cout << "+\t" << s.name << " = " << &d.value[0]
<< "\n";
break; break;
case table::BOOL: case table::BOOL:
cout << "+\t" << s.name << " = " cout << "+\t" << s.name << " = "
<< (d.value[0] ? "YES" : "NO") << "\n"; << (d.value[0] ? "YES" : "NO") << "\n";
break; break;
case table::HEX: case table::HEX:
cout << "+\t" << s.name << " = " << d.value << "\n"; cout << "+\t" << s.name << " = " << d.value << "\n";
break; break;
case table::DEC: case table::DEC:
cout << "+\t" << s.name << " = "; cout << "+\t" << s.name << " = ";
if (d.value.size() > 0) if (d.value.size() > 0)
cout << dec << (unsigned) d.value[0]; cout << dec << (unsigned) d.value[0];
for (unsigned i = 1; i < d.value.size(); i++) for (unsigned i = 1; i < d.value.size(); i++)
cout << dec << "." << (unsigned) d.value[i]; cout << dec << "." << (unsigned) d.value[i];
cout << "\n"; cout << "\n";
break; break;
case table::ACTION: case table::ACTION:
cout << "Error:" << s.name cout << "Error:" << s.name
<< " is marked as 'action' but carries payload." << " is marked as 'action' but carries payload."
<< d.value << "\n"; << d.value << "\n";
break; break;
default: default:
cout << "+\t" << s.name << " = " << d.value << "\n"; cout << "+\t" << s.name << " = " << d.value << "\n";
break; break;
} }
} else { //empty }
else { //empty
cout << dec << ">\t" << s.name << "\n"; cout << dec << ">\t" << s.name << "\n";
} }
} else { //unknown id }
else { //unknown id
if (d.len > 0) { if (d.len > 0) {
cout << "##\t" << d.type << ":\n\t"; cout << "##\t" << d.type << ":\n\t";
cout << hex << d.value << dec << "\n"; cout << hex << d.value << dec << "\n";
} else { //empty }
else { //empty
cout << "#>\t" << d.type << "\n"; cout << "#>\t" << d.type << "\n";
} }
} }
@ -193,7 +203,8 @@ int Program::list() {
printHeader(a); printHeader(a);
if (options.flags.HEX) { if (options.flags.HEX) {
cout <<"Received Payload:\n"<<a.getBody()<<"\n"; cout <<"Received Payload:\n"<<a.getBody()<<"\n";
} else { }
else {
datasets d =a.getPayload(); datasets d =a.getPayload();
int b = a.getSwitchMac().hash(); int b = a.getSwitchMac().hash();
@ -416,8 +427,9 @@ int Program::set(Packet l, datasets t, Listener c) {
p.setHostMac(host.getMac()); p.setHostMac(host.getMac());
bytes n = options.user; bytes n = options.user;
bytes w = options.password; bytes w = options.password;
datasets ld = { { LOGIN_USER, (short) (n.size()), n }, { LOGIN_PASSWORD, datasets ld = {
(short) (w.size()), w } }; { LOGIN_USER, (short) (n.size()), n }, {
LOGIN_PASSWORD, (short) (w.size()), w } };
p.setPayload(ld + t); p.setPayload(ld + t);
sock->listen(c, Filter(Packet::CONFIRM).mac(l.getSwitchMac())); sock->listen(c, Filter(Packet::CONFIRM).mac(l.getSwitchMac()));
sock->send(p); sock->send(p);

View file

@ -17,34 +17,34 @@
#include "Socket.h" #include "Socket.h"
class Program { class Program {
private: private:
std::shared_ptr<boost::asio::io_service> io_service; std::shared_ptr<boost::asio::io_service> io_service;
std::shared_ptr<Socket> sock; std::shared_ptr<Socket> sock;
Host host = Host(); Host host = Host();
std::map<int, Switch> devices; std::map<int, Switch> devices;
int get(Packet, datasets, std::function<int(Packet)>); int get(Packet, datasets, std::function<int(Packet)>);
int set(Packet, datasets, std::function<int(Packet)>); int set(Packet, datasets, std::function<int(Packet)>);
int discover(std::function<int(Packet)>); int discover(std::function<int(Packet)>);
public: public:
Program() { Program() {
} }
void init(); void init();
int run(std::vector<std::string>); int run(std::vector<std::string>);
std::function<int()> callback = []() { std::function<int()> callback = []() {
return 0; return 0;
}; };
int list(); int list();
int sniff(); int sniff();
int encode(std::string); int encode(std::string);
int getProperty(std::vector<std::string>); int getProperty(std::vector<std::string>);
int setProperty(std::map<std::string, std::string>); int setProperty(std::map<std::string, std::string>);
int save(); int save();
int restore(); int restore();
int flash(); int flash();
int reboot(); int reboot();
int reset(); int reset();
std::string input; std::string input;
}; };
#endif /* PROGRAM_H_ */ #endif /* PROGRAM_H_ */

View file

@ -57,14 +57,15 @@ void Socket::setHostIp(ipAddr ip) {
local_ip = ip; local_ip = ip;
} }
void Socket::clear(){ void Socket::clear() {
callback.clear(); callback.clear();
} }
void Socket::listen(Listener l, Filter f) { void Socket::listen(Listener l, Filter f) {
if (callback.find(f) == callback.end()) { if (callback.find(f) == callback.end()) {
callback.insert(ListenerPair(f, l)); callback.insert(ListenerPair(f, l));
} else { }
else {
callback[f] = l; callback[f] = l;
} }
receive(); receive();
@ -92,7 +93,8 @@ void Socket::receive() {
if (ec || bytes_recvd == 0) { if (ec || bytes_recvd == 0) {
//listen(); //listen();
// TODO distinguish error codes // TODO distinguish error codes
} else { }
else {
data.resize(bytes_recvd); data.resize(bytes_recvd);
Packet p = Packet(Packet::NONE); Packet p = Packet(Packet::NONE);
p.encode(data); p.encode(data);
@ -102,7 +104,8 @@ void Socket::receive() {
r.second(p); r.second(p);
// std::cout<<"pass"<<std::endl; // std::cout<<"pass"<<std::endl;
break; break;
} else { }
else {
// std::cout<<"no pass"<<std::endl; // std::cout<<"no pass"<<std::endl;
} }
} }

View file

@ -23,28 +23,28 @@ typedef std::function<int(Packet)> Listener;
typedef std::pair<Filter, Listener> ListenerPair; typedef std::pair<Filter, Listener> ListenerPair;
class Socket { class Socket {
public: public:
Socket(boost::asio::io_service&); Socket(boost::asio::io_service&);
virtual ~Socket(); virtual ~Socket();
void init(short, short); void init(short, short);
void clear(); void clear();
void send(Packet); void send(Packet);
void setHostIp(ipAddr); void setHostIp(ipAddr);
void listen(Listener l, Filter f = Filter()); void listen(Listener l, Filter f = Filter());
private: private:
void receive(); void receive();
void settimeout(); void settimeout();
boost::asio::ip::udp::socket send_socket_; boost::asio::ip::udp::socket send_socket_;
boost::asio::ip::udp::socket receive_socket_; boost::asio::ip::udp::socket receive_socket_;
boost::asio::ip::udp::endpoint broadcast_endpoint_; boost::asio::ip::udp::endpoint broadcast_endpoint_;
boost::asio::ip::udp::endpoint remote_endpoint_; boost::asio::ip::udp::endpoint remote_endpoint_;
boost::asio::ip::udp::endpoint wildcard_endpoint_; boost::asio::ip::udp::endpoint wildcard_endpoint_;
boost::asio::ip::udp::endpoint local_endpoint_; boost::asio::ip::udp::endpoint local_endpoint_;
boost::asio::deadline_timer timer; boost::asio::deadline_timer timer;
bytes data = bytes(MAX_LENGTH); bytes data = bytes(MAX_LENGTH);
ipAddr local_ip; ipAddr local_ip;
std::map<Filter, Listener> callback = { }; std::map<Filter, Listener> callback = { };
}; };

View file

@ -22,8 +22,8 @@ int Switch::set(pair<string, string> str) {
std::string Switch::get(std::string str) { std::string Switch::get(std::string str) {
std::string ret; std::string ret;
switch (caseArg(str.c_str())) { switch (caseArg(str.c_str())) {
case caseArg("ip"): case caseArg("ip"):
ret = "0.0.0.0"; ret = "0.0.0.0";
break; break;
} }
return ret; return ret;

View file

@ -14,85 +14,85 @@
int Switch::parse(std::string str) { int Switch::parse(std::string str) {
if (json.Parse(str.c_str()).HasParseError()) if (json.Parse(str.c_str()).HasParseError())
return 1; return 1;
if (options.debug_level>=1) if (options.debug_level >= 1)
std::cout << "\nParsing to document succeeded.\n"; std::cout << "\nParsing to document succeeded.\n";
if (json.IsObject()) { if (json.IsObject()) {
if (json.HasMember("hostname")) if (json.HasMember("hostname"))
settings.hostname = json["hostname"].GetString(); settings.hostname = json["hostname"].GetString();
if (json.HasMember("type")) if (json.HasMember("type"))
device.type = json["type"].GetString(); device.type = json["type"].GetString();
if (json.HasMember("hardware_version")) if (json.HasMember("hardware_version"))
device.hardware_version = json["hardware_version"].GetString(); device.hardware_version = json["hardware_version"].GetString();
if (json.HasMember("firmware_version")) if (json.HasMember("firmware_version"))
device.hardware_version = json["firmware_version"].GetString(); device.hardware_version = json["firmware_version"].GetString();
if (json.HasMember("ports") && json["ports"].IsArray()) { if (json.HasMember("ports") && json["ports"].IsArray()) {
const rapidjson::Value& a = json["ports"]; const rapidjson::Value& a = json["ports"];
for (rapidjson::SizeType i = 0; i < a.Size(); i++) for (rapidjson::SizeType i = 0; i < a.Size(); i++)
if (a[i].IsObject()) { if (a[i].IsObject()) {
port p; port p;
if (a[i].HasMember("id") && a[i]["id"].IsInt()) { if (a[i].HasMember("id") && a[i]["id"].IsInt()) {
p.id = a[i]["id"].GetInt(); p.id = a[i]["id"].GetInt();
std::cout << a[i]["id"].GetInt() << "\n"; std::cout << a[i]["id"].GetInt() << "\n";
} }
ports.push_back(p); ports.push_back(p);
} }
} }
if (json.HasMember("vlans") && json["vlans"].IsArray()) { if (json.HasMember("vlans") && json["vlans"].IsArray()) {
const rapidjson::Value& a = json["vlans"]; const rapidjson::Value& a = json["vlans"];
for (rapidjson::SizeType i = 0; i < a.Size(); i++) for (rapidjson::SizeType i = 0; i < a.Size(); i++)
if (a[i].IsObject()) { if (a[i].IsObject()) {
vlan v; vlan v;
if (a[i].HasMember("name") && a[i]["name"].IsString()) { if (a[i].HasMember("name") && a[i]["name"].IsString()) {
v.name = a[i]["name"].GetString(); v.name = a[i]["name"].GetString();
std::cout << a[i]["name"].GetString() << "\n"; std::cout << a[i]["name"].GetString() << "\n";
} }
vlans.push_back(v); vlans.push_back(v);
} }
} }
} }
/* /*
{ {
const rapidjson::Value& a = json["a"]; const rapidjson::Value& a = json["a"];
assert(a.IsArray()); assert(a.IsArray());
for (rapidjson::SizeType i = 0; i < a.Size(); i++) for (rapidjson::SizeType i = 0; i < a.Size(); i++)
printf("a[%d] = %d\n", i, a[i].GetInt()); printf("a[%d] = %d\n", i, a[i].GetInt());
int y = a[0].GetInt(); int y = a[0].GetInt();
(void) y; (void) y;
*/ */
return 0; return 0;
} }
std::string Switch::toString() { std::string Switch::toString() {
if (!json.IsObject()) { if (!json.IsObject()) {
json.SetObject(); json.SetObject();
} }
rapidjson::Document::AllocatorType& allocator = json.GetAllocator(); rapidjson::Document::AllocatorType& allocator = json.GetAllocator();
json.AddMember("hostname", jsonNode(settings.hostname, json), allocator); json.AddMember("hostname", jsonNode(settings.hostname, json), allocator);
json.AddMember("ip", jsonNode(settings.ip_addr, json), allocator); json.AddMember("ip", jsonNode(settings.ip_addr, json), allocator);
json.AddMember("netmask", jsonNode(settings.ip_mask, json), allocator); json.AddMember("netmask", jsonNode(settings.ip_mask, json), allocator);
json.AddMember("gateway", jsonNode(settings.gateway, json), allocator); json.AddMember("gateway", jsonNode(settings.gateway, json), allocator);
json.AddMember("type", jsonNode(device.type, json), allocator); json.AddMember("type", jsonNode(device.type, json), allocator);
json.AddMember("hardware_version", jsonNode(device.hardware_version, json), json.AddMember("hardware_version", jsonNode(device.hardware_version, json),
allocator); allocator);
json.AddMember("firmware_version", jsonNode(device.firmware_version, json), json.AddMember("firmware_version", jsonNode(device.firmware_version, json),
allocator); allocator);
json.AddMember("ports", jsonNode(ports, json), allocator); json.AddMember("ports", jsonNode(ports, json), allocator);
json.AddMember("vlans", jsonNode(vlans, json), allocator); json.AddMember("vlans", jsonNode(vlans, json), allocator);
rapidjson::StringBuffer sb; rapidjson::StringBuffer sb;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(sb); rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(sb);
json.Accept(writer); json.Accept(writer);
return sb.GetString(); return sb.GetString();
} }

View file

@ -27,44 +27,44 @@ int Switch::print() {
int Switch::parse(dataset d) { int Switch::parse(dataset d) {
switch (d.type) { switch (d.type) {
case TYPE: case TYPE:
device.type = d.value; device.type = d.value;
break; break;
case MAC: case MAC:
device.mac = d.value; device.mac = d.value;
break; break;
case FIRMWARE_VERSION: case FIRMWARE_VERSION:
device.firmware_version = d.value; device.firmware_version = d.value;
break; break;
case HARDWARE_VERSION: case HARDWARE_VERSION:
device.hardware_version = d.value; device.hardware_version = d.value;
break; break;
case PORTS: case PORTS:
device.ports = d.value[0]; device.ports = d.value[0];
break; break;
case HOSTNAME: case HOSTNAME:
settings.hostname = d.value; settings.hostname = d.value;
break; break;
case IP_ADDR: case IP_ADDR:
settings.ip_addr = d.value; settings.ip_addr = d.value;
break; break;
case IP_MASK: case IP_MASK:
settings.ip_mask = d.value; settings.ip_mask = d.value;
break; break;
case GATEWAY: case GATEWAY:
settings.gateway = d.value; settings.gateway = d.value;
break; break;
case DHCP_ENABLED: case DHCP_ENABLED:
settings.dhcp = d.value[0]; settings.dhcp = d.value[0];
break; break;
case LOOP_PREVENTION: case LOOP_PREVENTION:
settings.loop_prevention = d.value[0]; settings.loop_prevention = d.value[0];
break; break;
case QOS_BASIC_ENABLED: case QOS_BASIC_ENABLED:
settings.qos_enabled = d.value[0]; settings.qos_enabled = d.value[0];
break; break;
case VLAN_ENABLED: case VLAN_ENABLED:
settings.vlan_enabled = d.value[0]; settings.vlan_enabled = d.value[0];
break; break;
} }
return 0; return 0;

View file

@ -18,85 +18,87 @@
#define DEFAULT_PASS "admin" #define DEFAULT_PASS "admin"
enum CntStatus { enum CntStatus {
OPEN, SHORT OPEN, SHORT
}; };
struct vlan { struct vlan {
int vlan_id; int vlan_id;
std::string name; std::string name;
std::vector<byte> tagged_member; std::vector<byte> tagged_member;
std::vector<byte> untagged_member; std::vector<byte> untagged_member;
}; };
struct trunk { struct trunk {
int trunk_id; int trunk_id;
std::vector<byte> member; std::vector<byte> member;
}; };
struct port { struct port {
byte id; byte id;
byte status; byte status;
int pvid; int pvid;
struct { struct {
//port_settings //port_settings
} settings; } settings;
struct { struct {
//port_statistics //port_statistics
} stats; } stats;
struct { struct {
//bandwidth_control_ingress //bandwidth_control_ingress
//bandwidth_control_egress //bandwidth_control_egress
} bw_control; } bw_control;
struct { struct {
//storm_control //storm_control
} storm_control; } storm_control;
struct { struct {
CntStatus status; CntStatus status;
int fault_distace; int fault_distace;
} test; } test;
//qos_basic //qos_basic
}; };
class Switch { class Switch {
public: public:
Switch() { Switch() {
} }
int parse(datasets); int parse(datasets);
int parse(dataset); int parse(dataset);
int parse(std::string); int parse(std::string);
int set(std::pair<std::string,std::string>); int set(std::pair<std::string, std::string>);
std::string get(std::string); std::string get(std::string);
std::string toString(); std::string toString();
int print(); int print();
struct { struct {
std::string type; std::string type;
std::string hardware_version; std::string hardware_version;
std::string firmware_version; std::string firmware_version;
macAddr mac { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }; macAddr mac {
int ports; 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
} device; int ports;
struct { } device;
std::string password = DEFAULT_PASS; struct {
std::string username = DEFAULT_USER; std::string password = DEFAULT_PASS;
std::string hostname; std::string username = DEFAULT_USER;
ipAddr ip_addr { 0, 0, 0, 0, }; std::string hostname;
ipAddr ip_mask; ipAddr ip_addr {
ipAddr gateway; 0, 0, 0, 0, };
bool dhcp; ipAddr ip_mask;
bool loop_prevention; ipAddr gateway;
bool qos_enabled; bool dhcp;
bool vlan_enabled; bool loop_prevention;
//mtu_vlan bool qos_enabled;
} settings; bool vlan_enabled;
//mtu_vlan
} settings;
private: private:
rapidjson::Document json; rapidjson::Document json;
std::vector<vlan> vlans; std::vector<vlan> vlans;
std::vector<port> ports; std::vector<port> ports;
}; };
#endif /* SWITCH_H_ */ #endif /* SWITCH_H_ */

View file

@ -20,117 +20,117 @@
#include "table.h" #include "table.h"
class macAddr: public std::array<byte, 6> { class macAddr: public std::array<byte, 6> {
public: public:
friend std::ostream& operator<<(std::ostream& out, const macAddr& arr) { friend std::ostream& operator<<(std::ostream& out, const macAddr& arr) {
out << std::hex << std::setw(2) << std::setfill('0') out << std::hex << std::setw(2) << std::setfill('0')
<< (unsigned) arr[0]; << (unsigned) arr[0];
for (unsigned i = 1; i < 6; i++) { for (unsigned i = 1; i < 6; i++) {
out << ":" << std::setw(2) << std::setfill('0') out << ":" << std::setw(2) << std::setfill('0')
<< (unsigned) arr[i]; << (unsigned) arr[i];
}
return out;
} }
return out;
}
macAddr() { macAddr() {
*this= {0,0,0,0,0,0}; *this= {0,0,0,0,0,0};
}
macAddr(std::initializer_list<byte> s) {
int i = 0;
for (byte b : s) {
if(i<6) (*this)[i++]=b;
else break;
} }
}
macAddr(bytes bts) { macAddr(std::initializer_list<byte> s) {
int i = 0; int i = 0;
for (byte b : bts) { for (byte b : s) {
if(i<6) (*this)[i++]=b; if(i<6) (*this)[i++]=b;
else break; else break;
}
} }
}
int hash() { macAddr(bytes bts) {
int ret=0; int i = 0;
for (unsigned i = 0; i < 6; i++) { for (byte b : bts) {
ret = (ret*33) ^ (*this)[i]; if(i<6) (*this)[i++]=b;
else break;
}
} }
return ret;
}
bool operator==(const macAddr &A) { int hash() {
for (unsigned i = 0; i < 6; i++) { int ret=0;
if(A[i]!=(*this)[i])return false; for (unsigned i = 0; i < 6; i++) {
ret = (ret*33) ^ (*this)[i];
}
return ret;
} }
return true;
}
bool operator!=(const macAddr &A) { bool operator==(const macAddr &A) {
for (unsigned i = 0; i < 6; i++) { for (unsigned i = 0; i < 6; i++) {
if(A[i]!=(*this)[i])return true; if(A[i]!=(*this)[i])return false;
}
return true;
} }
return false;
}
};
/* bool operator!=(const macAddr &A) {
class mac_addr : public std::array<unsigned char, 6> { for (unsigned i = 0; i < 6; i++) {
public: if(A[i]!=(*this)[i])return true;
typedef std::array<unsigned char, 6> super; }
return false;
}
};
using super::super; /*
class mac_addr : public std::array<unsigned char, 6> {
public:
typedef std::array<unsigned char, 6> super;
mac_addr{00, 00, 00, 000}; using super::super;
};
*/ mac_addr{00, 00, 00, 000};
};
*/
class ipAddr: public std::array<byte, 4> { class ipAddr: public std::array<byte, 4> {
public: public:
ipAddr() { ipAddr() {
*this= {0,0,0,0,0,0}; *this= {0,0,0,0,0,0};
}
ipAddr(std::initializer_list<byte> s) {
int i = 0;
for (byte b : s) {
if(i<4) (*this)[i++]=b;
else break;
} }
}
ipAddr(bytes bts) { ipAddr(std::initializer_list<byte> s) {
int i = 0; int i = 0;
for (byte b : bts) { for (byte b : s) {
if(i<4) (*this)[i++]=b; if(i<4) (*this)[i++]=b;
else break; else break;
}
} }
}
friend std::ostream& operator<<(std::ostream& out, ipAddr& arr) { ipAddr(bytes bts) {
out << std::dec << (unsigned) arr[0]; int i = 0;
for (unsigned i = 1; i < 4; i++) { for (byte b : bts) {
out << "." << (unsigned) arr[i]; if(i<4) (*this)[i++]=b;
else break;
}
} }
return out;
} friend std::ostream& operator<<(std::ostream& out, ipAddr& arr) {
}; out << std::dec << (unsigned) arr[0];
for (unsigned i = 1; i < 4; i++) {
out << "." << (unsigned) arr[i];
}
return out;
}
};
namespace smrtlink { namespace smrtlink {
constexpr unsigned int caseArg(const char* str, int h = 0) { constexpr unsigned int caseArg(const char* str, int h = 0) {
return !str[h] ? 5381 : (caseArg(str, h + 1) * 33) ^ str[h]; return !str[h] ? 5381 : (caseArg(str, h + 1) * 33) ^ str[h];
} }
} }
template<typename T> template<typename T>
std::vector<T> operator+(const std::vector<T> &A, const std::vector<T> &B) { std::vector<T> operator+(const std::vector<T> &A, const std::vector<T> &B) {
std::vector<T> AB; std::vector<T> AB;
AB.reserve(A.size() + B.size()); // preallocate memory AB.reserve(A.size() + B.size()); // preallocate memory
AB.insert(AB.end(), A.begin(), A.end()); // add A; AB.insert(AB.end(), A.begin(), A.end()); // add A;
AB.insert(AB.end(), B.begin(), B.end()); // add B; AB.insert(AB.end(), B.begin(), B.end()); // add B;
return AB; return AB;
} }
@ -142,24 +142,24 @@ std::vector<T> &operator+=(std::vector<T> &A, const std::vector<T> &B) {
} }
struct Options { struct Options {
struct { struct {
bool HEX; bool HEX;
bool JSON; bool JSON;
bool PLAIN; bool PLAIN;
bool REVERSE; bool REVERSE;
bool HEADER; bool HEADER;
bool PERMANENT; bool PERMANENT;
bool WAIT; bool WAIT;
bool INTERACTIVE; bool INTERACTIVE;
} flags; } flags;
std::string user; std::string user;
std::string password; std::string password;
std::string interface; std::string interface;
std::string file; std::string file;
int debug_level = 0; int debug_level = 0;
int verbosity = 0; int verbosity = 0;
long timeout = 250U; long timeout = 250U;
}; };
#endif /* TYPES_H_ */ #endif /* TYPES_H_ */

View file

@ -7,23 +7,23 @@
#include "bytes.h" #include "bytes.h"
bytes bytes::readHex(std::string s){ bytes bytes::readHex(std::string s) {
vector ret; vector ret;
std::string delimiter = ":"; std::string delimiter = ":";
std::string token; std::string token;
size_t pos = 0; size_t pos = 0;
int hex; int hex;
byte b; byte b;
ret.resize(0); ret.resize(0);
while ((pos = s.find(delimiter)) != std::string::npos) { while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos); token = s.substr(0, pos);
sscanf(token.c_str(), "%x", &hex); sscanf(token.c_str(), "%x", &hex);
s.erase(0, pos + delimiter.length()); s.erase(0, pos + delimiter.length());
b = hex & 0xFF; b = hex & 0xFF;
ret.push_back(b); ret.push_back(b);
} }
sscanf(s.c_str(), "%x", &hex); sscanf(s.c_str(), "%x", &hex);
b = hex & 0xFF; b = hex & 0xFF;
ret.push_back(b); ret.push_back(b);
return ret; return ret;
} }

View file

@ -19,67 +19,69 @@
typedef unsigned char byte; typedef unsigned char byte;
class bytes: public std::vector<unsigned char> { class bytes: public std::vector<unsigned char> {
typedef std::vector<unsigned char> vector; typedef std::vector<unsigned char> vector;
public: public:
using vector::operator[]; using vector::operator[];
bytes() { bytes() {
} }
bytes(int n) : vector(n){ bytes(int n) :
} vector(n) {
}
bytes(std::string d) : vector(d.begin(), d.end()){ bytes(std::string d) :
this->push_back('\0'); vector(d.begin(), d.end()) {
} this->push_back('\0');
}
bytes(std::initializer_list<uint8_t> s) bytes(std::initializer_list<uint8_t> s) {
{ for (uint8_t b : s) {
for (uint8_t b : s) { this->push_back(b);
this->push_back(b); }
} }
}
bytes(const vector &B) { bytes(const vector &B) {
this->reserve(B.size()); this->reserve(B.size());
this->insert(this->begin(), B.begin(), B.end()); this->insert(this->begin(), B.begin(), B.end());
} }
bytes readHex(std::string); bytes readHex(std::string);
bytes operator=(const vector &B) { bytes operator=(const vector &B) {
this->reserve(B.size()); this->reserve(B.size());
this->insert(this->begin(), B.begin(), B.end()); this->insert(this->begin(), B.begin(), B.end());
return *this; return *this;
} }
bytes &operator+=(const bytes &B) { bytes &operator+=(const bytes &B) {
this->reserve(this->size() + B.size()); this->reserve(this->size() + B.size());
this->insert(this->end(), B.begin(), B.end()); this->insert(this->end(), B.begin(), B.end());
return *this; return *this;
} }
bytes operator+(const bytes &B) { bytes operator+(const bytes &B) {
bytes AB; bytes AB;
AB.reserve(this->size() + B.size()); AB.reserve(this->size() + B.size());
AB.insert(AB.end(), this->begin(), this->end()); AB.insert(AB.end(), this->begin(), this->end());
AB.insert(AB.end(), B.begin(), B.end()); AB.insert(AB.end(), B.begin(), B.end());
return AB; return AB;
} }
friend std::ostream& operator<<(std::ostream& out, const bytes& arr) { friend std::ostream& operator<<(std::ostream& out, const bytes& arr) {
if (arr.size() > 0) { if (arr.size() > 0) {
out << std::hex << std::setw(2) << std::setfill('0') out << std::hex << std::setw(2) << std::setfill('0')
<< (unsigned) arr[0]; << (unsigned) arr[0];
} }
for (unsigned i = 1; i < arr.size(); i++) { for (unsigned i = 1; i < arr.size(); i++) {
out << ":" << std::setw(2) << std::setfill('0') << (unsigned) arr[i]; out << ":" << std::setw(2) << std::setfill('0')
} << (unsigned) arr[i];
return out; }
} return out;
}
operator std::string() { operator std::string() {
std::string s(this->begin(),this->end()); std::string s(this->begin(), this->end());
return s; return s;
} }
}; };
#endif /* BYTES_H_ */ #endif /* BYTES_H_ */

View file

@ -12,29 +12,29 @@
#include "bytes.h" #include "bytes.h"
struct dataset { struct dataset {
short type; short type;
short len; short len;
bytes value; bytes value;
}; };
class datasets : public std::vector<dataset> { class datasets: public std::vector<dataset> {
public: public:
datasets(){}; datasets() {
datasets(std::initializer_list<dataset> s) }
{ datasets(std::initializer_list<dataset> s) {
for (dataset b : s) { for (dataset b : s) {
//(*this)[b.type]=b; //(*this)[b.type]=b;
push_back(b); push_back(b);
} }
} }
datasets operator+(const datasets &B) { datasets operator+(const datasets &B) {
datasets AB; datasets AB;
AB.reserve(this->size() + B.size()); AB.reserve(this->size() + B.size());
AB.insert(AB.end(), this->begin(), this->end()); AB.insert(AB.end(), this->begin(), this->end());
AB.insert(AB.end(), B.begin(), B.end()); AB.insert(AB.end(), B.begin(), B.end());
return AB; return AB;
} }
}; };
#endif /* DATASETS_H_ */ #endif /* DATASETS_H_ */

View file

@ -11,43 +11,43 @@
#include "jsonNode.h" #include "jsonNode.h"
jsonNode::jsonNode(const std::string &x, doc &root) { jsonNode::jsonNode(const std::string &x, doc &root) {
super(rapidjson::kStringType); super(rapidjson::kStringType);
char buffer[30]; char buffer[30];
int len = sprintf(buffer, "%s", x.c_str()); int len = sprintf(buffer, "%s", x.c_str());
this->SetString(buffer, static_cast<size_t>(len), root.GetAllocator()); this->SetString(buffer, static_cast<size_t>(len), root.GetAllocator());
memset(buffer, 0, sizeof(buffer)); memset(buffer, 0, sizeof(buffer));
} }
jsonNode::jsonNode(const ipAddr &x, doc &root) { jsonNode::jsonNode(const ipAddr &x, doc &root) {
super(rapidjson::kStringType); super(rapidjson::kStringType);
char buffer[16]; char buffer[16];
int len = sprintf(buffer, "%d.%d.%d.%d", x[0], x[1], x[2], x[3]); int len = sprintf(buffer, "%d.%d.%d.%d", x[0], x[1], x[2], x[3]);
this->SetString(buffer, static_cast<size_t>(len), root.GetAllocator()); this->SetString(buffer, static_cast<size_t>(len), root.GetAllocator());
memset(buffer, 0, sizeof(buffer)); memset(buffer, 0, sizeof(buffer));
} }
jsonNode::jsonNode(const macAddr &x, doc &root) { jsonNode::jsonNode(const macAddr &x, doc &root) {
super(rapidjson::kStringType); super(rapidjson::kStringType);
char buffer[18]; char buffer[18];
int len = sprintf(buffer, "%02x:%02x:%02x:%02x:%02x:%02x", x[0], x[1], x[2], int len = sprintf(buffer, "%02x:%02x:%02x:%02x:%02x:%02x", x[0], x[1], x[2],
x[3], x[4], x[5]); x[3], x[4], x[5]);
this->SetString(buffer, static_cast<size_t>(len), root.GetAllocator()); this->SetString(buffer, static_cast<size_t>(len), root.GetAllocator());
memset(buffer, 0, sizeof(buffer)); memset(buffer, 0, sizeof(buffer));
} }
jsonNode::jsonNode(const vlan &x, doc &root) { jsonNode::jsonNode(const vlan &x, doc &root) {
super(rapidjson::kObjectType); super(rapidjson::kObjectType);
AddMember("id", x.vlan_id, root.GetAllocator()); AddMember("id", x.vlan_id, root.GetAllocator());
AddMember("name", jsonNode(x.name, root), root.GetAllocator()); AddMember("name", jsonNode(x.name, root), root.GetAllocator());
AddMember("tagged-members", jsonNode(x.tagged_member, root), AddMember("tagged-members", jsonNode(x.tagged_member, root),
root.GetAllocator()); root.GetAllocator());
AddMember("untagged-members", jsonNode(x.untagged_member, root), AddMember("untagged-members", jsonNode(x.untagged_member, root),
root.GetAllocator()); root.GetAllocator());
} }
jsonNode::jsonNode(const port &x, doc &root) { jsonNode::jsonNode(const port &x, doc &root) {
super(rapidjson::kObjectType); super(rapidjson::kObjectType);
AddMember("id", x.id, root.GetAllocator()); AddMember("id", x.id, root.GetAllocator());
AddMember("status", x.status, root.GetAllocator()); AddMember("status", x.status, root.GetAllocator());
AddMember("pvid", x.pvid, root.GetAllocator()); AddMember("pvid", x.pvid, root.GetAllocator());
} }

View file

@ -13,26 +13,26 @@
#include "Switch.h" #include "Switch.h"
class jsonNode: public rapidjson::Value { class jsonNode: public rapidjson::Value {
typedef rapidjson::Value super; typedef rapidjson::Value super;
typedef rapidjson::Document doc; typedef rapidjson::Document doc;
public: public:
jsonNode(const std::string&, doc&); jsonNode(const std::string&, doc&);
jsonNode(const macAddr&, doc&); jsonNode(const macAddr&, doc&);
jsonNode(const ipAddr&, doc&); jsonNode(const ipAddr&, doc&);
jsonNode(const vlan&, doc&); jsonNode(const vlan&, doc&);
jsonNode(const port&, doc&); jsonNode(const port&, doc&);
template<class T> template<class T>
jsonNode(const T &templ_arg, doc &root){ jsonNode(const T &templ_arg, doc &root) {
std::cerr<<"Not serializable Type: "<<typeid(T).name()<<"\n"; std::cerr << "Not serializable Type: " << typeid(T).name() << "\n";
} }
template<class T> template<class T>
jsonNode(const std::vector<T> &x, doc &root) { jsonNode(const std::vector<T> &x, doc &root) {
super(rapidjson::kArrayType); super(rapidjson::kArrayType);
for (T y : x) for (T y : x)
PushBack(jsonNode(y, root), root.GetAllocator()); PushBack(jsonNode(y, root), root.GetAllocator());
} }
}; };
#endif /* JSONNODE_H_ */ #endif /* JSONNODE_H_ */

View file

@ -38,96 +38,101 @@ int main(int argc, char *argv[]) {
options.user = DEFAULT_USER; options.user = DEFAULT_USER;
options.password = DEFAULT_PASS; options.password = DEFAULT_PASS;
const struct option longopts[] = { { "version", no_argument, 0, 'V' }, { const struct option longopts[] = {
"verbose", no_argument, 0, 'v' }, { "help", no_argument, 0, 'h' }, { { "version", no_argument, 0, 'V' }, {
"reverse", no_argument, 0, 'r' }, "verbose", no_argument, 0, 'v' },
{ "permanent", no_argument, 0, 's' }, { "debug", optional_argument, { "help", no_argument, 0, 'h' }, {
0, 'd' }, { "password", required_argument, 0, 'P' }, { "reverse", no_argument, 0, 'r' },
"user", required_argument, 0, 'U' }, { "interface", { "permanent", no_argument, 0, 's' }, {
required_argument, 0, 'i' }, { "header", required_argument, "debug", optional_argument, 0, 'd' },
0, 'b' }, { "hex", required_argument, 0, 'x' }, { "file", { "password", required_argument, 0, 'P' }, {
required_argument, 0, 'f' }, { "timeout", required_argument, "user", required_argument, 0, 'U' },
0, 't' }, { "wait", required_argument, 0, 'w' }, { 0, 0, 0, { "interface", required_argument, 0, 'i' }, {
0 }, }; "header", required_argument, 0, 'b' },
{ "hex", required_argument, 0, 'x' }, {
"file", required_argument, 0, 'f' },
{ "timeout", required_argument, 0, 't' }, {
"wait", required_argument, 0, 'w' },
{ 0, 0, 0, 0 }, };
while ((opt = getopt_long(argc, argv, "bhrvVXIswxP:U:i:f:t:d::", longopts, while ((opt = getopt_long(argc, argv, "bhrvVXIswxP:U:i:f:t:d::", longopts,
&index)) != -1) { &index)) != -1) {
switch (opt) { switch (opt) {
case 'h': case 'h':
fprintf(stderr, VERSION); fprintf(stderr, VERSION);
fprintf(stderr, USAGE, argv[0]); fprintf(stderr, USAGE, argv[0]);
fprintf(stderr, HELP); fprintf(stderr, HELP);
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
break; break;
case 'V': case 'V':
fprintf(stderr, VERSION); fprintf(stderr, VERSION);
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
break; break;
case 'r': case 'r':
options.flags.REVERSE = true; options.flags.REVERSE = true;
break; break;
case 'b': case 'b':
options.flags.HEADER = true; options.flags.HEADER = true;
break; break;
case 'x': case 'x':
options.flags.HEX = true; options.flags.HEX = true;
break; break;
case 's': case 's':
options.flags.PERMANENT = true; options.flags.PERMANENT = true;
break; break;
case 'w': case 'w':
options.flags.WAIT = true; options.flags.WAIT = true;
break; break;
case 'X': case 'X':
options.flags.INTERACTIVE = true; options.flags.INTERACTIVE = true;
break; break;
case 'v': case 'v':
if (optarg != NULL) if (optarg != NULL)
options.verbosity = atoi(optarg); options.verbosity = atoi(optarg);
else else
options.verbosity++; options.verbosity++;
break; break;
case 'd': case 'd':
if (optarg != NULL) if (optarg != NULL)
options.debug_level = atoi(optarg); options.debug_level = atoi(optarg);
else else
options.debug_level++; options.debug_level++;
break; break;
case 't': case 't':
options.timeout = atol(optarg); options.timeout = atol(optarg);
break; break;
case 'f': case 'f':
options.file = std::string(optarg); options.file = std::string(optarg);
break; break;
case 'P': case 'P':
options.password = std::string(optarg); options.password = std::string(optarg);
break; break;
case 'U': case 'U':
options.user = std::string(optarg); options.user = std::string(optarg);
break; break;
case 'i': case 'i':
options.interface = std::string(optarg); options.interface = std::string(optarg);
break; break;
default: /* '?' */ default: /* '?' */
fprintf(stderr, "Unknown option\n"); fprintf(stderr, "Unknown option\n");
fprintf(stderr, USAGE, argv[0]); fprintf(stderr, USAGE, argv[0]);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
@ -152,7 +157,8 @@ int main(int argc, char *argv[]) {
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
fprintf(stderr, "Not yet implemented.\n"); fprintf(stderr, "Not yet implemented.\n");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} else if (optind < argc) { }
else if (optind < argc) {
vector<string> v; vector<string> v;
while (optind < argc) while (optind < argc)
v.push_back(argv[optind++]); v.push_back(argv[optind++]);

View file

@ -18,24 +18,24 @@ table::table(std::initializer_list<set> l) {
i++; i++;
} }
} }
const table::set table::operator[](std::string s){ const table::set table::operator[](std::string s) {
return *this->right[s]; return *this->right[s];
} }
const table::set table::operator[](short n){ const table::set table::operator[](short n) {
return *this->left[n]; return *this->left[n];
} }
bool table::exists(std::string s){ bool table::exists(std::string s) {
return !(right.find(s) == right.end()); return !(right.find(s) == right.end());
} }
bool table::exists(short n){ bool table::exists(short n) {
return !(left.find(n) == left.end()); return !(left.find(n) == left.end());
} }
short table::type(std::string s){ short table::type(std::string s) {
return this->right[s]->type; return this->right[s]->type;
} }
std::string table::id(short n){ std::string table::id(short n) {
return this->left[n]->id; return this->left[n]->id;
} }
std::string table::name(short n){ std::string table::name(short n) {
return this->left[n]->name; return this->left[n]->name;
} }

View file

@ -12,32 +12,32 @@
#include <vector> #include <vector>
class table { class table {
public: public:
enum A { enum A {
RW, RO, WO, NONE, UNKNOWN RW, RO, WO, NONE, UNKNOWN
}; };
enum F { enum F {
STRING, HEX, DEC, ACTION, BOOL, EMPTY STRING, HEX, DEC, ACTION, BOOL, EMPTY
}; };
struct set { struct set {
short type; short type;
F format; F format;
A action; A action;
std::string name; std::string name;
std::string id; std::string id;
}; };
table(std::initializer_list<set> l); table(std::initializer_list<set> l);
const table::set operator[](std::string); const table::set operator[](std::string);
const table::set operator[](short); const table::set operator[](short);
bool exists(std::string); bool exists(std::string);
bool exists(short); bool exists(short);
short type(std::string); short type(std::string);
std::string id(short); std::string id(short);
std::string name(short); std::string name(short);
private: private:
std::vector<set> data; std::vector<set> data;
std::map<short, set*> left; std::map<short, set*> left;
std::map<std::string, set*> right; std::map<std::string, set*> right;
}; };
#endif /* LOOKUPTABLE_H_ */ #endif /* LOOKUPTABLE_H_ */