statistics.cpp 26 KB

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