statistics_db.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. #include "statistics_db.h"
  2. #include <math.h>
  3. #include <iostream>
  4. #include <sstream>
  5. #include <fstream>
  6. #include <unistd.h>
  7. #include <stdio.h>
  8. /**
  9. * Creates a new statistics_db object. Opens an existing database located at database_path. If not existing, creates
  10. * a new database at database_path.
  11. * @param database_path The file path of the database.
  12. */
  13. statistics_db::statistics_db(std::string database_path) {
  14. // Append file extension if not present
  15. if (database_path.find(".sqlite3") == database_path.npos) {
  16. database_path += ".sqlite3";
  17. }
  18. // creates the DB if not existing, opens the DB for read+write access
  19. db.reset(new SQLite::Database(database_path, SQLite::OPEN_CREATE | SQLite::OPEN_READWRITE));
  20. // Read ports and services into portServices vector
  21. readPortServicesFromNmap();
  22. }
  23. /**
  24. * Writes the IP statistics into the database.
  25. * @param ipStatistics The IP statistics from class statistics.
  26. */
  27. void statistics_db::writeStatisticsIP(std::unordered_map<std::string, entry_ipStat> ipStatistics) {
  28. try {
  29. db->exec("DROP TABLE IF EXISTS ip_statistics");
  30. SQLite::Transaction transaction(*db);
  31. const char *createTable = "CREATE TABLE ip_statistics ( "
  32. "ipAddress TEXT, "
  33. "pktsReceived INTEGER, "
  34. "pktsSent INTEGER, "
  35. "kbytesReceived REAL, "
  36. "kbytesSent REAL, "
  37. "maxPktRate REAL,"
  38. "minPktRate REAL,"
  39. "ipClass TEXT COLLATE NOCASE, "
  40. "PRIMARY KEY(ipAddress));";
  41. db->exec(createTable);
  42. SQLite::Statement query(*db, "INSERT INTO ip_statistics VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
  43. for (auto it = ipStatistics.begin(); it != ipStatistics.end(); ++it) {
  44. entry_ipStat e = it->second;
  45. query.bind(1, it->first);
  46. query.bind(2, (int) e.pkts_received);
  47. query.bind(3, (int) e.pkts_sent);
  48. query.bind(4, e.kbytes_received);
  49. query.bind(5, e.kbytes_sent);
  50. query.bind(6, e.max_interval_pkt_rate);
  51. query.bind(7, e.min_interval_pkt_rate);
  52. query.bind(8, e.ip_class);
  53. query.exec();
  54. query.reset();
  55. }
  56. transaction.commit();
  57. }
  58. catch (std::exception &e) {
  59. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  60. }
  61. }
  62. /**
  63. * Writes the TTL distribution into the database.
  64. * @param ttlDistribution The TTL distribution from class statistics.
  65. */
  66. void statistics_db::writeStatisticsTTL(std::unordered_map<ipAddress_ttl, int> ttlDistribution) {
  67. try {
  68. db->exec("DROP TABLE IF EXISTS ip_ttl");
  69. SQLite::Transaction transaction(*db);
  70. const char *createTable = "CREATE TABLE ip_ttl ("
  71. "ipAddress TEXT,"
  72. "ttlValue INTEGER,"
  73. "ttlCount INTEGER,"
  74. "PRIMARY KEY(ipAddress,ttlValue));";
  75. db->exec(createTable);
  76. SQLite::Statement query(*db, "INSERT INTO ip_ttl VALUES (?, ?, ?)");
  77. for (auto it = ttlDistribution.begin(); it != ttlDistribution.end(); ++it) {
  78. ipAddress_ttl e = it->first;
  79. query.bind(1, e.ipAddress);
  80. query.bind(2, e.ttlValue);
  81. query.bind(3, it->second);
  82. query.exec();
  83. query.reset();
  84. }
  85. transaction.commit();
  86. }
  87. catch (std::exception &e) {
  88. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  89. }
  90. }
  91. /**
  92. * Writes the MSS distribution into the database.
  93. * @param mssDistribution The MSS distribution from class statistics.
  94. */
  95. void statistics_db::writeStatisticsMSS(std::unordered_map<ipAddress_mss, int> mssDistribution) {
  96. try {
  97. db->exec("DROP TABLE IF EXISTS tcp_mss");
  98. SQLite::Transaction transaction(*db);
  99. const char *createTable = "CREATE TABLE tcp_mss ("
  100. "ipAddress TEXT,"
  101. "mssValue INTEGER,"
  102. "mssCount INTEGER,"
  103. "PRIMARY KEY(ipAddress,mssValue));";
  104. db->exec(createTable);
  105. SQLite::Statement query(*db, "INSERT INTO tcp_mss VALUES (?, ?, ?)");
  106. for (auto it = mssDistribution.begin(); it != mssDistribution.end(); ++it) {
  107. ipAddress_mss e = it->first;
  108. query.bind(1, e.ipAddress);
  109. query.bind(2, e.mssValue);
  110. query.bind(3, it->second);
  111. query.exec();
  112. query.reset();
  113. }
  114. transaction.commit();
  115. }
  116. catch (std::exception &e) {
  117. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  118. }
  119. }
  120. /**
  121. * Writes the ToS distribution into the database.
  122. * @param tosDistribution The ToS distribution from class statistics.
  123. */
  124. void statistics_db::writeStatisticsToS(std::unordered_map<ipAddress_tos, int> tosDistribution) {
  125. try {
  126. db->exec("DROP TABLE IF EXISTS ip_tos");
  127. SQLite::Transaction transaction(*db);
  128. const char *createTable = "CREATE TABLE ip_tos ("
  129. "ipAddress TEXT,"
  130. "tosValue INTEGER,"
  131. "tosCount INTEGER,"
  132. "PRIMARY KEY(ipAddress,tosValue));";
  133. db->exec(createTable);
  134. SQLite::Statement query(*db, "INSERT INTO ip_tos VALUES (?, ?, ?)");
  135. for (auto it = tosDistribution.begin(); it != tosDistribution.end(); ++it) {
  136. ipAddress_tos e = it->first;
  137. query.bind(1, e.ipAddress);
  138. query.bind(2, e.tosValue);
  139. query.bind(3, it->second);
  140. query.exec();
  141. query.reset();
  142. }
  143. transaction.commit();
  144. }
  145. catch (std::exception &e) {
  146. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  147. }
  148. }
  149. /**
  150. * Writes the window size distribution into the database.
  151. * @param winDistribution The window size distribution from class statistics.
  152. */
  153. void statistics_db::writeStatisticsWin(std::unordered_map<ipAddress_win, int> winDistribution) {
  154. try {
  155. db->exec("DROP TABLE IF EXISTS tcp_win");
  156. SQLite::Transaction transaction(*db);
  157. const char *createTable = "CREATE TABLE tcp_win ("
  158. "ipAddress TEXT,"
  159. "winSize INTEGER,"
  160. "winCount INTEGER,"
  161. "PRIMARY KEY(ipAddress,winSize));";
  162. db->exec(createTable);
  163. SQLite::Statement query(*db, "INSERT INTO tcp_win VALUES (?, ?, ?)");
  164. for (auto it = winDistribution.begin(); it != winDistribution.end(); ++it) {
  165. ipAddress_win e = it->first;
  166. query.bind(1, e.ipAddress);
  167. query.bind(2, e.winSize);
  168. query.bind(3, it->second);
  169. query.exec();
  170. query.reset();
  171. }
  172. transaction.commit();
  173. }
  174. catch (std::exception &e) {
  175. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  176. }
  177. }
  178. /**
  179. * Writes the protocol distribution into the database.
  180. * @param protocolDistribution The protocol distribution from class statistics.
  181. */
  182. void statistics_db::writeStatisticsProtocols(std::unordered_map<ipAddress_protocol, entry_protocolStat> protocolDistribution) {
  183. try {
  184. db->exec("DROP TABLE IF EXISTS ip_protocols");
  185. SQLite::Transaction transaction(*db);
  186. const char *createTable = "CREATE TABLE ip_protocols ("
  187. "ipAddress TEXT,"
  188. "protocolName TEXT COLLATE NOCASE,"
  189. "protocolCount INTEGER,"
  190. "byteCount REAL,"
  191. "PRIMARY KEY(ipAddress,protocolName));";
  192. db->exec(createTable);
  193. SQLite::Statement query(*db, "INSERT INTO ip_protocols VALUES (?, ?, ?, ?)");
  194. for (auto it = protocolDistribution.begin(); it != protocolDistribution.end(); ++it) {
  195. ipAddress_protocol e = it->first;
  196. query.bind(1, e.ipAddress);
  197. query.bind(2, e.protocol);
  198. query.bind(3, it->second.count);
  199. query.bind(4, it->second.byteCount);
  200. query.exec();
  201. query.reset();
  202. }
  203. transaction.commit();
  204. }
  205. catch (std::exception &e) {
  206. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  207. }
  208. }
  209. /**
  210. * Writes the port statistics into the database.
  211. * @param portsStatistics The ports statistics from class statistics.
  212. */
  213. void statistics_db::writeStatisticsPorts(std::unordered_map<ipAddress_inOut_port, entry_portStat> portsStatistics) {
  214. try {
  215. db->exec("DROP TABLE IF EXISTS ip_ports");
  216. SQLite::Transaction transaction(*db);
  217. const char *createTable = "CREATE TABLE ip_ports ("
  218. "ipAddress TEXT,"
  219. "portDirection TEXT COLLATE NOCASE,"
  220. "portNumber INTEGER,"
  221. "portCount INTEGER,"
  222. "byteCount REAL,"
  223. "portProtocol TEXT COLLATE NOCASE,"
  224. "portService TEXT COLLATE NOCASE,"
  225. "PRIMARY KEY(ipAddress,portDirection,portNumber));";
  226. db->exec(createTable);
  227. SQLite::Statement query(*db, "INSERT INTO ip_ports VALUES (?, ?, ?, ?, ?, ?, ?)");
  228. for (auto it = portsStatistics.begin(); it != portsStatistics.end(); ++it) {
  229. ipAddress_inOut_port e = it->first;
  230. std::string portService = portServices[e.portNumber];
  231. if(portService.empty()) {
  232. if(portServices[{0}] == "unavailable") {portService = "unavailable";}
  233. else {portService = "unknown";}
  234. }
  235. query.bind(1, e.ipAddress);
  236. query.bind(2, e.trafficDirection);
  237. query.bind(3, e.portNumber);
  238. query.bind(4, it->second.count);
  239. query.bind(5, it->second.byteCount);
  240. query.bind(6, e.protocol);
  241. query.bind(7, portService);
  242. query.exec();
  243. query.reset();
  244. }
  245. transaction.commit();
  246. }
  247. catch (std::exception &e) {
  248. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  249. }
  250. }
  251. /**
  252. * Writes the IP address -> MAC address mapping into the database.
  253. * @param IpMacStatistics The IP address -> MAC address mapping from class statistics.
  254. */
  255. void statistics_db::writeStatisticsIpMac(std::unordered_map<std::string, std::string> IpMacStatistics) {
  256. try {
  257. db->exec("DROP TABLE IF EXISTS ip_mac");
  258. SQLite::Transaction transaction(*db);
  259. const char *createTable = "CREATE TABLE ip_mac ("
  260. "ipAddress TEXT,"
  261. "macAddress TEXT COLLATE NOCASE,"
  262. "PRIMARY KEY(ipAddress));";
  263. db->exec(createTable);
  264. SQLite::Statement query(*db, "INSERT INTO ip_mac VALUES (?, ?)");
  265. for (auto it = IpMacStatistics.begin(); it != IpMacStatistics.end(); ++it) {
  266. query.bind(1, it->first);
  267. query.bind(2, it->second);
  268. query.exec();
  269. query.reset();
  270. }
  271. transaction.commit();
  272. }
  273. catch (std::exception &e) {
  274. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  275. }
  276. }
  277. /**
  278. * Writes general file statistics into the database.
  279. * @param packetCount The number of packets in the PCAP file.
  280. * @param captureDuration The duration of the capture (format: SS.mmmmmm).
  281. * @param timestampFirstPkt The timestamp of the first packet in the PCAP file.
  282. * @param timestampLastPkt The timestamp of the last packet in the PCAP file.
  283. * @param avgPacketRate The average packet rate (#packets / capture duration).
  284. * @param avgPacketSize The average packet size.
  285. * @param avgPacketsSentPerHost The average packets sent per host.
  286. * @param avgBandwidthIn The average incoming bandwidth.
  287. * @param avgBandwidthOut The average outgoing bandwidth.
  288. */
  289. void statistics_db::writeStatisticsFile(int packetCount, float captureDuration, std::string timestampFirstPkt,
  290. std::string timestampLastPkt, float avgPacketRate, float avgPacketSize,
  291. float avgPacketsSentPerHost, float avgBandwidthIn, float avgBandwidthOut) {
  292. try {
  293. db->exec("DROP TABLE IF EXISTS file_statistics");
  294. SQLite::Transaction transaction(*db);
  295. const char *createTable = "CREATE TABLE file_statistics ("
  296. "packetCount INTEGER,"
  297. "captureDuration TEXT,"
  298. "timestampFirstPacket TEXT,"
  299. "timestampLastPacket TEXT,"
  300. "avgPacketRate REAL,"
  301. "avgPacketSize REAL,"
  302. "avgPacketsSentPerHost REAL,"
  303. "avgBandwidthIn REAL,"
  304. "avgBandwidthOut REAL);";
  305. db->exec(createTable);
  306. SQLite::Statement query(*db, "INSERT INTO file_statistics VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
  307. query.bind(1, packetCount);
  308. query.bind(2, captureDuration);
  309. query.bind(3, timestampFirstPkt);
  310. query.bind(4, timestampLastPkt);
  311. query.bind(5, avgPacketRate);
  312. query.bind(6, avgPacketSize);
  313. query.bind(7, avgPacketsSentPerHost);
  314. query.bind(8, avgBandwidthIn);
  315. query.bind(9, avgBandwidthOut);
  316. query.exec();
  317. transaction.commit();
  318. }
  319. catch (std::exception &e) {
  320. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  321. }
  322. }
  323. /**
  324. * Writes the conversation statistics into the database.
  325. * @param convStatistics The conversation from class statistics.
  326. */
  327. void statistics_db::writeStatisticsConv(std::unordered_map<conv, entry_convStat> convStatistics){
  328. try {
  329. db->exec("DROP TABLE IF EXISTS conv_statistics");
  330. SQLite::Transaction transaction(*db);
  331. const char *createTable = "CREATE TABLE conv_statistics ("
  332. "ipAddressA TEXT,"
  333. "portA INTEGER,"
  334. "ipAddressB TEXT,"
  335. "portB INTEGER,"
  336. "pktsCount INTEGER,"
  337. "avgPktRate REAL,"
  338. "avgDelay INTEGER,"
  339. "minDelay INTEGER,"
  340. "maxDelay INTEGER,"
  341. "PRIMARY KEY(ipAddressA,portA,ipAddressB,portB));";
  342. db->exec(createTable);
  343. SQLite::Statement query(*db, "INSERT INTO conv_statistics VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
  344. // Calculate average of inter-arrival times and average packet rate
  345. for (auto it = convStatistics.begin(); it != convStatistics.end(); ++it) {
  346. conv f = it->first;
  347. entry_convStat e = it->second;
  348. if (e.pkts_count > 1){
  349. int sumDelay = 0;
  350. int minDelay = -1;
  351. int maxDelay = -1;
  352. for (int i = 0; (unsigned) i < e.interarrival_time.size(); i++) {
  353. sumDelay += e.interarrival_time[i].count();
  354. if (maxDelay < e.interarrival_time[i].count())
  355. maxDelay = e.interarrival_time[i].count();
  356. if (minDelay > e.interarrival_time[i].count() || minDelay == -1)
  357. minDelay = e.interarrival_time[i].count();
  358. }
  359. if (e.interarrival_time.size() > 0)
  360. e.avg_interarrival_time = (std::chrono::microseconds) sumDelay / e.interarrival_time.size(); // average
  361. else e.avg_interarrival_time = (std::chrono::microseconds) 0;
  362. std::chrono::microseconds start_timesttamp = e.pkts_timestamp[0];
  363. std::chrono::microseconds end_timesttamp = e.pkts_timestamp.back();
  364. std::chrono::microseconds conn_duration = end_timesttamp - start_timesttamp;
  365. e.avg_pkt_rate = (float) e.pkts_count * 1000000 / conn_duration.count(); // pkt per sec
  366. query.bind(1, f.ipAddressA);
  367. query.bind(2, f.portA);
  368. query.bind(3, f.ipAddressB);
  369. query.bind(4, f.portB);
  370. query.bind(5, (int) e.pkts_count);
  371. query.bind(6, (float) e.avg_pkt_rate);
  372. query.bind(7, (int) e.avg_interarrival_time.count());
  373. query.bind(8, minDelay);
  374. query.bind(9, maxDelay);
  375. query.exec();
  376. query.reset();
  377. }
  378. }
  379. transaction.commit();
  380. }
  381. catch (std::exception &e) {
  382. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  383. }
  384. }
  385. /**
  386. * Writes the interval statistics into the database.
  387. * @param intervalStatistics The interval entries from class statistics.
  388. */
  389. void statistics_db::writeStatisticsInterval(std::unordered_map<std::string, entry_intervalStat> intervalStatistics){
  390. try {
  391. db->exec("DROP TABLE IF EXISTS interval_statistics");
  392. SQLite::Transaction transaction(*db);
  393. const char *createTable = "CREATE TABLE interval_statistics ("
  394. "lastPktTimestamp TEXT,"
  395. "pktsCount INTEGER,"
  396. "kBytes REAL,"
  397. "ipSrcEntropy REAL,"
  398. "ipDstEntropy REAL,"
  399. "ipSrcCumEntropy REAL,"
  400. "ipDstCumEntropy REAL,"
  401. "payloadCount INTEGER,"
  402. "incorrectTCPChecksumCount INTEGER,"
  403. "correctTCPChecksumCount INTEGER,"
  404. "newIPCount INTEGER,"
  405. "newPortCount INTEGER,"
  406. "newTTLCount INTEGER,"
  407. "newWinSizeCount INTEGER,"
  408. "newToSCount INTEGER,"
  409. "newMSSCount INTEGER,"
  410. "PRIMARY KEY(lastPktTimestamp));";
  411. db->exec(createTable);
  412. SQLite::Statement query(*db, "INSERT INTO interval_statistics VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  413. for (auto it = intervalStatistics.begin(); it != intervalStatistics.end(); ++it) {
  414. std::string t = it->first;
  415. entry_intervalStat e = it->second;
  416. query.bind(1, t);
  417. query.bind(2, (int)e.pkts_count);
  418. query.bind(3, e.kbytes);
  419. query.bind(4, e.ip_src_entropy);
  420. query.bind(5, e.ip_dst_entropy);
  421. query.bind(6, e.ip_src_cum_entropy);
  422. query.bind(7, e.ip_dst_cum_entropy);
  423. query.bind(8, e.payload_count);
  424. query.bind(9, e.incorrect_tcp_checksum_count);
  425. query.bind(10, e.correct_tcp_checksum_count);
  426. query.bind(11, e.novel_ip_count);
  427. query.bind(12, e.novel_port_count);
  428. query.bind(13, e.novel_ttl_count);
  429. query.bind(14, e.novel_win_size_count);
  430. query.bind(15, e.novel_tos_count);
  431. query.bind(16, e.novel_mss_count);
  432. query.exec();
  433. query.reset();
  434. }
  435. transaction.commit();
  436. }
  437. catch (std::exception &e) {
  438. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  439. }
  440. }
  441. void statistics_db::writeDbVersion(){
  442. try {
  443. SQLite::Transaction transaction(*db);
  444. SQLite::Statement query(*db, std::string("PRAGMA user_version = ") + std::to_string(DB_VERSION) + ";");
  445. query.exec();
  446. transaction.commit();
  447. }
  448. catch (std::exception &e) {
  449. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  450. }
  451. }
  452. /**
  453. * Reads all ports and their corresponding services from nmap-services-tcp.csv and stores them into portServices vector.
  454. */
  455. void statistics_db::readPortServicesFromNmap()
  456. {
  457. std::string portnumber;
  458. std::string service;
  459. std::string dump;
  460. std::string nmapPath = getNmapPath();
  461. std::ifstream reader;
  462. reader.open(nmapPath, std::ios::in);
  463. if(reader.is_open())
  464. {
  465. getline(reader, dump);
  466. while(!reader.eof())
  467. {
  468. getline(reader, portnumber, ',');
  469. getline(reader, service, ',');
  470. getline(reader, dump);
  471. if(!service.empty() && !portnumber.empty())
  472. {
  473. portServices.insert({std::stoi(portnumber), service});
  474. }
  475. }
  476. reader.close();
  477. }
  478. else
  479. {
  480. std::cerr << "WARNING: " << nmapPath << " could not be opened! PortServices can't be read!" << std::endl;
  481. portServices.insert({0, "unavailable"});
  482. }
  483. }
  484. /**
  485. * Gets the path to nmap-services-tcp.csv and makes sure the file is reached from any working directory within "/code"
  486. * because the working directory can be different when running tests. Checks if the file/path exists and warns the user.
  487. */
  488. std::string statistics_db::getNmapPath()
  489. {
  490. //The different working directory paths according to how the database is built:
  491. //<ID2T> stands for the directory id2t.sh is located in
  492. //From tests(e.g. pycharm) /<ID2T>/code/Test
  493. //From run_tests.sh /<ID2T>/code
  494. //From id2t.sh /<ID2T>
  495. std::string filename = "nmap-services-tcp.csv";
  496. std::string resourcesDir = "/resources/";
  497. std::string codeDir = "/code";
  498. std::string testDir = "/code/Test";
  499. char buff[FILENAME_MAX];
  500. // Working directory
  501. std::string dir(getcwd(buff, FILENAME_MAX));
  502. // Check if working directory is id2t.sh directory(try to reach file from working directory)
  503. if(pathExists(dir + resourcesDir + filename))
  504. {
  505. return dir + resourcesDir + filename;
  506. }
  507. // If working directory is test directory(happens if tests are called from pycharm for example)
  508. else if(dir.rfind(testDir) == (dir.size()-testDir.size()))
  509. {
  510. // Remove test directory from path
  511. dir = dir.substr(0, (dir.size()-testDir.size()));
  512. }
  513. // If working directory is code directory(happens if tests are called with testscript)
  514. else if(dir.rfind(codeDir) == (dir.size()-codeDir.size()))
  515. {
  516. // Remove code directory from path
  517. dir = dir.substr(0, (dir.size()-codeDir.size()));
  518. }
  519. dir = dir + resourcesDir + filename;
  520. return dir;
  521. }
  522. bool statistics_db::pathExists(std::string path)
  523. {
  524. std::ifstream file;
  525. file.open(path, std::ios::in);
  526. if(file.is_open())
  527. {
  528. file.close();
  529. return true;
  530. }
  531. else
  532. {
  533. return false;
  534. }
  535. }
  536. /**
  537. * Writes the unrecognized PDUs into the database.
  538. * @param unrecognized_PDUs The unrecognized PDUs from class statistics.
  539. */
  540. void statistics_db::writeStatisticsUnrecognizedPDUs(std::unordered_map<unrecognized_PDU, unrecognized_PDU_stat>
  541. unrecognized_PDUs) {
  542. try {
  543. db->exec("DROP TABLE IF EXISTS unrecognized_pdus");
  544. SQLite::Transaction transaction(*db);
  545. const char *createTable = "CREATE TABLE unrecognized_pdus ("
  546. "srcMac TEXT COLLATE NOCASE,"
  547. "dstMac TEXT COLLATE NOCASE,"
  548. "etherType INTEGER,"
  549. "pktCount INTEGER,"
  550. "timestampLastOccurrence TEXT,"
  551. "PRIMARY KEY(srcMac,dstMac,etherType));";
  552. db->exec(createTable);
  553. SQLite::Statement query(*db, "INSERT INTO unrecognized_pdus VALUES (?, ?, ?, ?, ?)");
  554. for (auto it = unrecognized_PDUs.begin(); it != unrecognized_PDUs.end(); ++it) {
  555. unrecognized_PDU e = it->first;
  556. query.bind(1, e.srcMacAddress);
  557. query.bind(2, e.dstMacAddress);
  558. query.bind(3, e.typeNumber);
  559. query.bind(4, it->second.count);
  560. query.bind(5, it->second.timestamp_last_occurrence);
  561. query.exec();
  562. query.reset();
  563. }
  564. transaction.commit();
  565. }
  566. catch (std::exception &e) {
  567. std::cout << "Exception in statistics_db: " << e.what() << std::endl;
  568. }
  569. }