statistics.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <math.h>
  5. #include <sstream>
  6. #include <SQLiteCpp/SQLiteCpp.h>
  7. #include "statistics_db.h"
  8. #include "statistics.h"
  9. #include "utilities.h"
  10. using namespace Tins;
  11. // Aidmar
  12. /**
  13. * Checks if there is a payload and increments payloads counter.
  14. * @param pdu_l4 The packet that should be checked if it has a payload or not.
  15. */
  16. void statistics::checkPayload(const PDU *pdu_l4) {
  17. if(this->getDoTests()) {
  18. // pdu_l4: Tarnsport layer 4
  19. int pktSize = pdu_l4->size();
  20. int headerSize = pdu_l4->header_size(); // TCP/UDP header
  21. int payloadSize = pktSize - headerSize;
  22. if (payloadSize > 0)
  23. payloadCount++;
  24. }
  25. }
  26. // Aidmar
  27. /**
  28. * Checks the correctness of TCP checksum and increments counter if the checksum was incorrect.
  29. * @param ipAddressSender The source IP.
  30. * @param ipAddressReceiver The destination IP.
  31. * @param tcpPkt The packet to get checked.
  32. */
  33. void statistics::checkTCPChecksum(std::string ipAddressSender, std::string ipAddressReceiver, TCP tcpPkt) {
  34. if(this->getDoTests()) {
  35. if(check_tcpChecksum(ipAddressSender, ipAddressReceiver, tcpPkt))
  36. correctTCPChecksumCount++;
  37. else incorrectTCPChecksumCount++;
  38. }
  39. }
  40. // Aidmar
  41. /**
  42. * Calculates entropy of source and destination IPs for last time interval.
  43. * @param intervalStartTimestamp The timstamp where the interval starts.
  44. */
  45. std::vector<float> statistics::calculateLastIntervalIPsEntropy(std::chrono::microseconds intervalStartTimestamp){
  46. if(this->getDoTests()) {
  47. std::vector<int> IPsSrcPktsCounts;
  48. std::vector<int> IPsDstPktsCounts;
  49. std::vector<float> IPsSrcProb;
  50. std::vector<float> IPsDstProb;
  51. int pktsSent = 0, pktsReceived = 0;
  52. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  53. int indexStartSent = getClosestIndex(i->second.pktsSentTimestamp, intervalStartTimestamp);
  54. int IPsSrcPktsCount = i->second.pktsSentTimestamp.size() - indexStartSent;
  55. IPsSrcPktsCounts.push_back(IPsSrcPktsCount);
  56. pktsSent += IPsSrcPktsCount;
  57. int indexStartReceived = getClosestIndex(i->second.pktsReceivedTimestamp, intervalStartTimestamp);
  58. int IPsDstPktsCount = i->second.pktsReceivedTimestamp.size() - indexStartReceived;
  59. IPsDstPktsCounts.push_back(IPsDstPktsCount);
  60. pktsReceived += IPsDstPktsCount;
  61. }
  62. for (auto i = IPsSrcPktsCounts.begin(); i != IPsSrcPktsCounts.end(); i++) {
  63. IPsSrcProb.push_back((float) *i / pktsSent);
  64. }
  65. for (auto i = IPsDstPktsCounts.begin(); i != IPsDstPktsCounts.end(); i++) {
  66. IPsDstProb.push_back((float) *i / pktsReceived);
  67. }
  68. // Calculate IP source entropy
  69. float IPsSrcEntropy = 0;
  70. for (unsigned i = 0; i < IPsSrcProb.size(); i++) {
  71. if (IPsSrcProb[i] > 0)
  72. IPsSrcEntropy += -IPsSrcProb[i] * log2(IPsSrcProb[i]);
  73. }
  74. // Calculate IP destination entropy
  75. float IPsDstEntropy = 0;
  76. for (unsigned i = 0; i < IPsDstProb.size(); i++) {
  77. if (IPsDstProb[i] > 0)
  78. IPsDstEntropy += -IPsDstProb[i] * log2(IPsDstProb[i]);
  79. }
  80. std::vector<float> entropies = {IPsSrcEntropy, IPsDstEntropy};
  81. return entropies;
  82. }
  83. else {
  84. return {-1, -1};
  85. }
  86. }
  87. // Aidmar
  88. /**
  89. * Calculates cumulative entropy of source and destination IPs, i.e., the entropy for packets from the beginning of the pcap file.
  90. */
  91. std::vector<float> statistics::calculateIPsCumEntropy(){
  92. if(this->getDoTests()) {
  93. std::vector <std::string> IPs;
  94. std::vector <float> IPsSrcProb;
  95. std::vector <float> IPsDstProb;
  96. //std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
  97. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  98. IPs.push_back(i->first);
  99. IPsSrcProb.push_back((float)i->second.pkts_sent/packetCount);
  100. IPsDstProb.push_back((float)i->second.pkts_received/packetCount);
  101. }
  102. // Calculate IP source entropy
  103. float IPsSrcEntropy = 0;
  104. for(unsigned i=0; i < IPsSrcProb.size();i++){
  105. if (IPsSrcProb[i] > 0)
  106. IPsSrcEntropy += - IPsSrcProb[i]*log2(IPsSrcProb[i]);
  107. }
  108. // Calculate IP destination entropy
  109. float IPsDstEntropy = 0;
  110. for(unsigned i=0; i < IPsDstProb.size();i++){
  111. if (IPsDstProb[i] > 0)
  112. IPsDstEntropy += - IPsDstProb[i]*log2(IPsDstProb[i]);
  113. }
  114. std::vector<float> entropies = {IPsSrcEntropy, IPsDstEntropy};
  115. return entropies;
  116. }
  117. else {
  118. return {-1, -1};
  119. }
  120. }
  121. // Aidmar
  122. /**
  123. * Calculates sending packet rate for each IP in last time interval. Finds min and max packet rate and adds them to ip_statistics map.
  124. * @param intervalStartTimestamp The timstamp where the interval starts.
  125. */
  126. void statistics::calculateIPIntervalPacketRate(std::chrono::duration<int, std::micro> interval, std::chrono::microseconds intervalStartTimestamp){
  127. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  128. int indexStartSent = getClosestIndex(i->second.pktsSentTimestamp, intervalStartTimestamp);
  129. int IPsSrcPktsCount = i->second.pktsSentTimestamp.size() - indexStartSent;
  130. float interval_pkt_rate = (float) IPsSrcPktsCount * 1000000 / interval.count(); // used 10^6 because interval in microseconds
  131. i->second.interval_pkt_rate.push_back(interval_pkt_rate);
  132. if(interval_pkt_rate > i->second.max_pkt_rate || i->second.max_pkt_rate == 0)
  133. i->second.max_pkt_rate = interval_pkt_rate;
  134. if(interval_pkt_rate < i->second.min_pkt_rate || i->second.min_pkt_rate == 0)
  135. i->second.min_pkt_rate = interval_pkt_rate;
  136. }
  137. }
  138. // Aidmar
  139. /**
  140. * Registers statistical data for last time interval. Calculates packet rate. Calculates IPs entropy. Calculates IPs cumulative entropy.
  141. * @param intervalStartTimestamp The timstamp where the interval starts.
  142. * @param intervalEndTimestamp The timstamp where the interval ends.
  143. * @param previousPacketCount The total number of packets in last interval.
  144. */
  145. void statistics::addIntervalStat(std::chrono::duration<int, std::micro> interval, std::chrono::microseconds intervalStartTimestamp, std::chrono::microseconds intervalEndTimestamp){
  146. // Add packet rate for each IP to ip_statistics map
  147. calculateIPIntervalPacketRate(interval, intervalStartTimestamp);
  148. std::vector<float> ipEntopies = calculateLastIntervalIPsEntropy(intervalStartTimestamp);
  149. std::vector<float> ipCumEntopies = calculateIPsCumEntropy();
  150. std::string lastPktTimestamp_s = std::to_string(intervalEndTimestamp.count());
  151. std::string intervalStartTimestamp_s = std::to_string(intervalStartTimestamp.count());
  152. // The intervalStartTimestamp_s is the previous interval lastPktTimestamp_s
  153. interval_statistics[lastPktTimestamp_s].pkts_count = packetCount - lastIntervalCumPktCount;
  154. interval_statistics[lastPktTimestamp_s].kbytes = (float(sumPacketSize - lastIntervalCumSumPktSize) / 1024);
  155. interval_statistics[lastPktTimestamp_s].payload_count = payloadCount - lastIntervalPayloadCount;
  156. interval_statistics[lastPktTimestamp_s].incorrect_checksum_count = incorrectTCPChecksumCount - lastIntervalIncorrectTCPChecksumCount;
  157. interval_statistics[lastPktTimestamp_s].correct_checksum_count = correctTCPChecksumCount - lastIntervalCorrectTCPChecksumCount;
  158. interval_statistics[lastPktTimestamp_s].invalid_tos_count = invalidToSCount - lastIntervalInvalidToSCount;
  159. interval_statistics[lastPktTimestamp_s].valid_tos_count = validToSCount - lastIntervalValidToSCount;
  160. interval_statistics[lastPktTimestamp_s].new_ip_count = ip_statistics.size() - lastIntervalCumNewIPCount;
  161. interval_statistics[lastPktTimestamp_s].new_ttl_count = ttl_values.size() - lastIntervalCumNewTTLCount;
  162. interval_statistics[lastPktTimestamp_s].new_win_size_count = win_values.size() - lastIntervalCumNewWinSizeCount;
  163. interval_statistics[lastPktTimestamp_s].new_tos_count = tos_values.size() - lastIntervalCumNewToSCount;
  164. interval_statistics[lastPktTimestamp_s].new_mss_count = mss_values.size() - lastIntervalCumNewMSSCount;
  165. //std::cout<<invalidToSCount<<","<<validToSCount<<"\n";
  166. lastIntervalPayloadCount = payloadCount;
  167. lastIntervalIncorrectTCPChecksumCount = incorrectTCPChecksumCount;
  168. lastIntervalCorrectTCPChecksumCount = correctTCPChecksumCount;
  169. lastIntervalInvalidToSCount = invalidToSCount;
  170. lastIntervalValidToSCount = validToSCount;
  171. lastIntervalCumPktCount = packetCount;
  172. lastIntervalCumSumPktSize = sumPacketSize;
  173. lastIntervalCumNewIPCount = ip_statistics.size();
  174. lastIntervalCumNewTTLCount = ttl_values.size();
  175. lastIntervalCumNewWinSizeCount = win_values.size();
  176. lastIntervalCumNewToSCount = tos_values.size();
  177. lastIntervalCumNewMSSCount = mss_values.size();
  178. if(ipEntopies.size()>1){
  179. interval_statistics[lastPktTimestamp_s].ip_src_entropy = ipEntopies[0];
  180. interval_statistics[lastPktTimestamp_s].ip_dst_entropy = ipEntopies[1];
  181. }
  182. if(ipCumEntopies.size()>1){
  183. interval_statistics[lastPktTimestamp_s].ip_src_cum_entropy = ipCumEntopies[0];
  184. interval_statistics[lastPktTimestamp_s].ip_dst_cum_entropy = ipCumEntopies[1];
  185. }
  186. }
  187. // Aidmar
  188. /**
  189. * Registers statistical data for a sent packet in a given conversation (two IPs, two ports).
  190. * Increments the counter packets_A_B or packets_B_A.
  191. * Adds the timestamp of the packet in pkts_A_B_timestamp or pkts_B_A_timestamp.
  192. * @param ipAddressSender The sender IP address.
  193. * @param sport The source port.
  194. * @param ipAddressReceiver The receiver IP address.
  195. * @param dport The destination port.
  196. * @param timestamp The timestamp of the packet.
  197. */
  198. void statistics::addConvStat(std::string ipAddressSender,int sport,std::string ipAddressReceiver,int dport, std::chrono::microseconds timestamp){
  199. conv f1 = {ipAddressReceiver, dport, ipAddressSender, sport};
  200. conv f2 = {ipAddressSender, sport, ipAddressReceiver, dport};
  201. // if already exist A(ipAddressReceiver, dport), B(ipAddressSender, sport) conversation
  202. if (conv_statistics.count(f1)>0){
  203. conv_statistics[f1].pkts_count++;
  204. if(conv_statistics[f1].pkts_count<=3)
  205. conv_statistics[f1].pkts_delay.push_back(std::chrono::duration_cast<std::chrono::microseconds> (timestamp - conv_statistics[f1].pkts_timestamp.back()));
  206. conv_statistics[f1].pkts_timestamp.push_back(timestamp);
  207. }
  208. else{
  209. conv_statistics[f2].pkts_count++;
  210. if(conv_statistics[f2].pkts_timestamp.size()>0 && conv_statistics[f2].pkts_count<=3 )
  211. conv_statistics[f2].pkts_delay.push_back(std::chrono::duration_cast<std::chrono::microseconds> (timestamp - conv_statistics[f2].pkts_timestamp.back()));
  212. conv_statistics[f2].pkts_timestamp.push_back(timestamp);
  213. }
  214. }
  215. // Aidmar
  216. /**
  217. * Increments the packet counter for the given IP address and MSS value.
  218. * @param ipAddress The IP address whose MSS packet counter should be incremented.
  219. * @param mssValue The MSS value of the packet.
  220. */
  221. void statistics::incrementMSScount(std::string ipAddress, int mssValue) {
  222. mss_values[mssValue]++;
  223. mss_distribution[{ipAddress, mssValue}]++;
  224. }
  225. // Aidmar
  226. /**
  227. * Increments the packet counter for the given IP address and window size.
  228. * @param ipAddress The IP address whose window size packet counter should be incremented.
  229. * @param winSize The window size of the packet.
  230. */
  231. void statistics::incrementWinCount(std::string ipAddress, int winSize) {
  232. win_values[winSize]++;
  233. win_distribution[{ipAddress, winSize}]++;
  234. }
  235. /**
  236. * Increments the packet counter for the given IP address and TTL value.
  237. * @param ipAddress The IP address whose TTL packet counter should be incremented.
  238. * @param ttlValue The TTL value of the packet.
  239. */
  240. void statistics::incrementTTLcount(std::string ipAddress, int ttlValue) {
  241. ttl_values[ttlValue]++;
  242. ttl_distribution[{ipAddress, ttlValue}]++;
  243. }
  244. /**
  245. * Increments the packet counter for the given IP address and ToS value.
  246. * @param ipAddress The IP address whose ToS packet counter should be incremented.
  247. * @param tosValue The ToS value of the packet.
  248. */
  249. void statistics::incrementToScount(std::string ipAddress, int tosValue) {
  250. tos_values[tosValue]++;
  251. tos_distribution[{ipAddress, tosValue}]++;
  252. }
  253. /**
  254. * Increments the protocol counter for the given IP address and protocol.
  255. * @param ipAddress The IP address whose protocol packet counter should be incremented.
  256. * @param protocol The protocol of the packet.
  257. */
  258. void statistics::incrementProtocolCount(std::string ipAddress, std::string protocol) {
  259. protocol_distribution[{ipAddress, protocol}]++;
  260. }
  261. /**
  262. * Returns the number of packets seen for the given IP address and protocol.
  263. * @param ipAddress The IP address whose packet count is wanted.
  264. * @param protocol The protocol whose packet count is wanted.
  265. * @return an integer: the number of packets
  266. */
  267. int statistics::getProtocolCount(std::string ipAddress, std::string protocol) {
  268. return protocol_distribution[{ipAddress, protocol}];
  269. }
  270. /**
  271. * Increments the packet counter for
  272. * - the given sender IP address with outgoing port and
  273. * - the given receiver IP address with incoming port.
  274. * @param ipAddressSender The IP address of the packet sender.
  275. * @param outgoingPort The port used by the sender.
  276. * @param ipAddressReceiver The IP address of the packet receiver.
  277. * @param incomingPort The port used by the receiver.
  278. */
  279. void statistics::incrementPortCount(std::string ipAddressSender, int outgoingPort, std::string ipAddressReceiver,
  280. int incomingPort) {
  281. ip_ports[{ipAddressSender, "out", outgoingPort}]++;
  282. ip_ports[{ipAddressReceiver, "in", incomingPort}]++;
  283. }
  284. /**
  285. * Creates a new statistics object.
  286. */
  287. statistics::statistics(void) {
  288. }
  289. /**
  290. * Stores the assignment IP address -> MAC address.
  291. * @param ipAddress The IP address belonging to the given MAC address.
  292. * @param macAddress The MAC address belonging to the given IP address.
  293. */
  294. void statistics::assignMacAddress(std::string ipAddress, std::string macAddress) {
  295. ip_mac_mapping[ipAddress] = macAddress;
  296. }
  297. /**
  298. * Registers statistical data for a sent packet. Increments the counter packets_sent for the sender and
  299. * packets_received for the receiver. Adds the bytes as kbytes_sent (sender) and kybtes_received (receiver).
  300. * @param ipAddressSender The IP address of the packet sender.
  301. * @param ipAddressReceiver The IP address of the packet receiver.
  302. * @param bytesSent The packet's size.
  303. */
  304. void statistics::addIpStat_packetSent(std::string filePath, std::string ipAddressSender, std::string ipAddressReceiver, long bytesSent, std::chrono::microseconds timestamp) {
  305. // Aidmar - Adding IP as a sender for first time
  306. if(ip_statistics[ipAddressSender].pkts_sent==0){
  307. // Add the IP class
  308. ip_statistics[ipAddressSender].ip_class = getIPv4Class(ipAddressSender);
  309. }
  310. // Aidmar - Adding IP as a receiver for first time
  311. if(ip_statistics[ipAddressReceiver].pkts_received==0){
  312. // Add the IP class
  313. ip_statistics[ipAddressReceiver].ip_class = getIPv4Class(ipAddressReceiver);
  314. }
  315. // Update stats for packet sender
  316. ip_statistics[ipAddressSender].kbytes_sent += (float(bytesSent) / 1024);
  317. ip_statistics[ipAddressSender].pkts_sent++;
  318. // Aidmar
  319. ip_statistics[ipAddressSender].pktsSentTimestamp.push_back(timestamp);
  320. // Update stats for packet receiver
  321. ip_statistics[ipAddressReceiver].kbytes_received += (float(bytesSent) / 1024);
  322. ip_statistics[ipAddressReceiver].pkts_received++;
  323. // Aidmar
  324. ip_statistics[ipAddressReceiver].pktsReceivedTimestamp.push_back(timestamp);
  325. }
  326. // Aidmar - comment out
  327. /**
  328. * Registers a value of the TCP option Maximum Segment Size (MSS).
  329. * @param ipAddress The IP address which sent the TCP packet.
  330. * @param MSSvalue The MSS value found.
  331. */
  332. //void statistics::addMSS(std::string ipAddress, int MSSvalue) {
  333. // ip_sumMss[ipAddress] += MSSvalue;
  334. //}
  335. /**
  336. * Setter for the timestamp_firstPacket field.
  337. * @param ts The timestamp of the first packet in the PCAP file.
  338. */
  339. void statistics::setTimestampFirstPacket(Tins::Timestamp ts) {
  340. timestamp_firstPacket = ts;
  341. }
  342. /**
  343. * Setter for the timestamp_lastPacket field.
  344. * @param ts The timestamp of the last packet in the PCAP file.
  345. */
  346. void statistics::setTimestampLastPacket(Tins::Timestamp ts) {
  347. timestamp_lastPacket = ts;
  348. }
  349. // Aidmar
  350. /**
  351. * Getter for the timestamp_firstPacket field.
  352. */
  353. Tins::Timestamp statistics::getTimestampFirstPacket() {
  354. return timestamp_firstPacket;
  355. }
  356. /**
  357. * Getter for the timestamp_lastPacket field.
  358. */
  359. Tins::Timestamp statistics::getTimestampLastPacket() {
  360. return timestamp_lastPacket;
  361. }
  362. /**
  363. * Getter for the packetCount field.
  364. */
  365. int statistics::getPacketCount() {
  366. return packetCount;
  367. }
  368. /**
  369. * Getter for the sumPacketSize field.
  370. */
  371. int statistics::getSumPacketSize() {
  372. return sumPacketSize;
  373. }
  374. /**
  375. * Calculates the capture duration.
  376. * @return a formatted string HH:MM:SS.mmmmmm with
  377. * HH: hour, MM: minute, SS: second, mmmmmm: microseconds
  378. */
  379. std::string statistics::getCaptureDurationTimestamp() const {
  380. // Calculate duration
  381. time_t t = (timestamp_lastPacket.seconds() - timestamp_firstPacket.seconds());
  382. time_t ms = (timestamp_lastPacket.microseconds() - timestamp_firstPacket.microseconds());
  383. long int hour = t / 3600;
  384. long int remainder = (t - hour * 3600);
  385. long int minute = remainder / 60;
  386. long int second = (remainder - minute * 60) % 60;
  387. long int microseconds = ms;
  388. // Build desired output format: YYYY-mm-dd hh:mm:ss
  389. char out[64];
  390. sprintf(out, "%02ld:%02ld:%02ld.%06ld ", hour, minute, second, microseconds);
  391. return std::string(out);
  392. }
  393. /**
  394. * Calculates the capture duration.
  395. * @return a formatted string SS.mmmmmm with
  396. * S: seconds (UNIX time), mmmmmm: microseconds
  397. */
  398. float statistics::getCaptureDurationSeconds() const {
  399. timeval d;
  400. d.tv_sec = timestamp_lastPacket.seconds() - timestamp_firstPacket.seconds();
  401. d.tv_usec = timestamp_lastPacket.microseconds() - timestamp_firstPacket.microseconds();
  402. char tmbuf[64], buf[64];
  403. auto nowtm = localtime(&(d.tv_sec));
  404. strftime(tmbuf, sizeof(tmbuf), "%S", nowtm);
  405. snprintf(buf, sizeof(buf), "%s.%06u", tmbuf, (uint) d.tv_usec);
  406. return std::stof(std::string(buf));
  407. }
  408. /**
  409. * Creates a timestamp based on a time_t seconds (UNIX time format) and microseconds.
  410. * @param seconds
  411. * @param microseconds
  412. * @return a formatted string Y-m-d H:M:S.m with
  413. * Y: year, m: month, d: day, H: hour, M: minute, S: second, m: microseconds
  414. */
  415. std::string statistics::getFormattedTimestamp(time_t seconds, suseconds_t microseconds) const {
  416. timeval tv;
  417. tv.tv_sec = seconds;
  418. tv.tv_usec = microseconds;
  419. char tmbuf[64], buf[64];
  420. auto nowtm = localtime(&(tv.tv_sec));
  421. strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%d %H:%M:%S", nowtm);
  422. snprintf(buf, sizeof(buf), "%s.%06u", tmbuf, (uint) tv.tv_usec);
  423. return std::string(buf);
  424. }
  425. /**
  426. * Calculates the statistics for a given IP address.
  427. * @param ipAddress The IP address whose statistics should be calculated.
  428. * @return a ip_stats struct containing statistical data derived by the statistical data collected.
  429. */
  430. ip_stats statistics::getStatsForIP(std::string ipAddress) {
  431. float duration = getCaptureDurationSeconds();
  432. entry_ipStat ipStatEntry = ip_statistics[ipAddress];
  433. ip_stats s;
  434. s.bandwidthKBitsIn = (ipStatEntry.kbytes_received / duration) * 8;
  435. s.bandwidthKBitsOut = (ipStatEntry.kbytes_sent / duration) * 8;
  436. s.packetPerSecondIn = (ipStatEntry.pkts_received / duration);
  437. s.packetPerSecondOut = (ipStatEntry.pkts_sent / duration);
  438. s.AvgPacketSizeSent = (ipStatEntry.kbytes_sent / ipStatEntry.pkts_sent);
  439. s.AvgPacketSizeRecv = (ipStatEntry.kbytes_received / ipStatEntry.pkts_received);
  440. // Aidmar - comment out
  441. //int sumMSS = ip_sumMss[ipAddress];
  442. //int tcpPacketsSent = getProtocolCount(ipAddress, "TCP");
  443. //s.AvgMaxSegmentSizeTCP = ((sumMSS > 0 && tcpPacketsSent > 0) ? (sumMSS / tcpPacketsSent) : 0);
  444. return s;
  445. }
  446. /**
  447. * Increments the packet counter.
  448. */
  449. void statistics::incrementPacketCount() {
  450. packetCount++;
  451. }
  452. /**
  453. * Prints the statistics of the PCAP and IP specific statistics for the given IP address.
  454. * @param ipAddress The IP address whose statistics should be printed. Can be empty "" to print only general file statistics.
  455. */
  456. void statistics::printStats(std::string ipAddress) {
  457. std::stringstream ss;
  458. ss << std::endl;
  459. ss << "Capture duration: " << getCaptureDurationSeconds() << " seconds" << std::endl;
  460. ss << "Capture duration (HH:MM:SS.mmmmmm): " << getCaptureDurationTimestamp() << std::endl;
  461. ss << "#Packets: " << packetCount << std::endl;
  462. ss << std::endl;
  463. // Print IP address specific statistics only if IP address was given
  464. if (ipAddress != "") {
  465. entry_ipStat e = ip_statistics[ipAddress];
  466. ss << "\n----- STATS FOR IP ADDRESS [" << ipAddress << "] -------" << std::endl;
  467. ss << std::endl << "KBytes sent: " << e.kbytes_sent << std::endl;
  468. ss << "KBytes received: " << e.kbytes_received << std::endl;
  469. ss << "Packets sent: " << e.pkts_sent << std::endl;
  470. ss << "Packets received: " << e.pkts_received << "\n\n";
  471. ip_stats is = getStatsForIP(ipAddress);
  472. ss << "Bandwidth IN: " << is.bandwidthKBitsIn << " kbit/s" << std::endl;
  473. ss << "Bandwidth OUT: " << is.bandwidthKBitsOut << " kbit/s" << std::endl;
  474. ss << "Packets per second IN: " << is.packetPerSecondIn << std::endl;
  475. ss << "Packets per second OUT: " << is.packetPerSecondOut << std::endl;
  476. ss << "Avg Packet Size Sent: " << is.AvgPacketSizeSent << " kbytes" << std::endl;
  477. ss << "Avg Packet Size Received: " << is.AvgPacketSizeRecv << " kbytes" << std::endl;
  478. //ss << "Avg MSS: " << is.AvgMaxSegmentSizeTCP << " bytes" << std::endl;
  479. }
  480. std::cout << ss.str();
  481. }
  482. /**
  483. * Derives general PCAP file statistics from the collected statistical data and
  484. * writes all data into a SQLite database, located at database_path.
  485. * @param database_path The path of the SQLite database file ending with .sqlite3.
  486. */
  487. void statistics::writeToDatabase(std::string database_path) {
  488. // Generate general file statistics
  489. float duration = getCaptureDurationSeconds();
  490. long sumPacketsSent = 0, senderCountIP = 0;
  491. float sumBandwidthIn = 0.0, sumBandwidthOut = 0.0;
  492. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  493. sumPacketsSent += i->second.pkts_sent;
  494. // Consumed bandwith (bytes) for sending packets
  495. sumBandwidthIn += (i->second.kbytes_received / duration);
  496. sumBandwidthOut += (i->second.kbytes_sent / duration);
  497. senderCountIP++;
  498. }
  499. float avgPacketRate = (packetCount / duration);
  500. long avgPacketSize = getAvgPacketSize();
  501. long avgPacketsSentPerHost = (sumPacketsSent / senderCountIP);
  502. float avgBandwidthInKBits = (sumBandwidthIn / senderCountIP) * 8;
  503. float avgBandwidthOutInKBits = (sumBandwidthOut / senderCountIP) * 8;
  504. // Create database and write information
  505. statistics_db db(database_path);
  506. db.writeStatisticsFile(packetCount, getCaptureDurationSeconds(),
  507. getFormattedTimestamp(timestamp_firstPacket.seconds(), timestamp_firstPacket.microseconds()),
  508. getFormattedTimestamp(timestamp_lastPacket.seconds(), timestamp_lastPacket.microseconds()),
  509. avgPacketRate, avgPacketSize, avgPacketsSentPerHost, avgBandwidthInKBits,
  510. avgBandwidthOutInKBits);
  511. db.writeStatisticsIP(ip_statistics);
  512. db.writeStatisticsTTL(ttl_distribution);
  513. db.writeStatisticsIpMac(ip_mac_mapping);
  514. //db.writeStatisticsMss(ip_sumMss);
  515. db.writeStatisticsPorts(ip_ports);
  516. db.writeStatisticsProtocols(protocol_distribution);
  517. // Aidmar
  518. db.writeStatisticsMss_dist(mss_distribution);
  519. db.writeStatisticsTos_dist(tos_distribution);
  520. db.writeStatisticsWin(win_distribution);
  521. db.writeStatisticsConv(conv_statistics);
  522. db.writeStatisticsInterval(interval_statistics);
  523. }
  524. /**
  525. * Returns the average packet size.
  526. * @return a float indicating the average packet size in kbytes.
  527. */
  528. float statistics::getAvgPacketSize() const {
  529. // AvgPktSize = (Sum of all packet sizes / #Packets)
  530. return (sumPacketSize / packetCount) / 1024;
  531. }
  532. /**
  533. * Adds the size of a packet (to be used to calculate the avg. packet size).
  534. * @param packetSize The size of the current packet in bytes.
  535. */
  536. void statistics::addPacketSize(uint32_t packetSize) {
  537. sumPacketSize += ((float) packetSize);
  538. }
  539. // Aidmar
  540. void statistics::setDoTests(bool var) {
  541. doTests = var;
  542. }
  543. bool statistics::getDoTests() {
  544. return doTests;
  545. }