statistics.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. // Aidmar
  2. #include <iostream>
  3. #include "statistics.h"
  4. #include <sstream>
  5. #include <SQLiteCpp/SQLiteCpp.h>
  6. #include "statistics_db.h"
  7. // Aidmar
  8. /**
  9. * Increments the packet counter for the given IP address and MSS value.
  10. * @param ipAddress The IP address whose MSS packet counter should be incremented.
  11. * @param mssValue The MSS value of the packet.
  12. */
  13. void statistics::incrementMSScount(std::string ipAddress, int mssValue) {
  14. mss_distribution[{ipAddress, mssValue}]++;
  15. }
  16. // Aidmar
  17. /**
  18. * Increments the packet counter for the given IP address and window size.
  19. * @param ipAddress The IP address whose window size packet counter should be incremented.
  20. * @param winSize The window size of the packet.
  21. */
  22. void statistics::incrementWinCount(std::string ipAddress, int winSize) {
  23. win_distribution[{ipAddress, winSize}]++;
  24. }
  25. /**
  26. * Increments the packet counter for the given IP address and TTL value.
  27. * @param ipAddress The IP address whose TTL packet counter should be incremented.
  28. * @param ttlValue The TTL value of the packet.
  29. */
  30. void statistics::incrementTTLcount(std::string ipAddress, int ttlValue) {
  31. ttl_distribution[{ipAddress, ttlValue}]++;
  32. }
  33. /**
  34. * Increments the protocol counter for the given IP address and protocol.
  35. * @param ipAddress The IP address whose protocol packet counter should be incremented.
  36. * @param protocol The protocol of the packet.
  37. */
  38. void statistics::incrementProtocolCount(std::string ipAddress, std::string protocol) {
  39. protocol_distribution[{ipAddress, protocol}]++;
  40. }
  41. /**
  42. * Returns the number of packets seen for the given IP address and protocol.
  43. * @param ipAddress The IP address whose packet count is wanted.
  44. * @param protocol The protocol whose packet count is wanted.
  45. * @return an integer: the number of packets
  46. */
  47. int statistics::getProtocolCount(std::string ipAddress, std::string protocol) {
  48. return protocol_distribution[{ipAddress, protocol}];
  49. }
  50. /**
  51. * Increments the packet counter for
  52. * - the given sender IP address with outgoing port and
  53. * - the given receiver IP address with incoming port.
  54. * @param ipAddressSender The IP address of the packet sender.
  55. * @param outgoingPort The port used by the sender.
  56. * @param ipAddressReceiver The IP address of the packet receiver.
  57. * @param incomingPort The port used by the receiver.
  58. */
  59. void statistics::incrementPortCount(std::string ipAddressSender, int outgoingPort, std::string ipAddressReceiver,
  60. int incomingPort) {
  61. ip_ports[{ipAddressSender, "out", outgoingPort}]++;
  62. ip_ports[{ipAddressReceiver, "in", incomingPort}]++;
  63. }
  64. /**
  65. * Creates a new statistics object.
  66. */
  67. statistics::statistics(void) {
  68. }
  69. /**
  70. * Stores the assignment IP address -> MAC address.
  71. * @param ipAddress The IP address belonging to the given MAC address.
  72. * @param macAddress The MAC address belonging to the given IP address.
  73. */
  74. void statistics::assignMacAddress(std::string ipAddress, std::string macAddress) {
  75. ip_mac_mapping[ipAddress] = macAddress;
  76. }
  77. /**
  78. * Registers statistical data for a sent packet. Increments the counter packets_sent for the sender and
  79. * packets_received for the receiver. Adds the bytes as kbytes_sent (sender) and kybtes_received (receiver).
  80. * @param ipAddressSender The IP address of the packet sender.
  81. * @param ipAddressReceiver The IP address of the packet receiver.
  82. * @param bytesSent The packet's size.
  83. */
  84. void statistics::addIpStat_packetSent(std::string ipAddressSender, std::string ipAddressReceiver, long bytesSent) {
  85. // Update stats for packet sender
  86. ip_statistics[ipAddressSender].kbytes_sent += (float(bytesSent) / 1024);
  87. ip_statistics[ipAddressSender].pkts_sent++;
  88. // Update stats for packet receiver
  89. ip_statistics[ipAddressReceiver].kbytes_received += (float(bytesSent) / 1024);
  90. ip_statistics[ipAddressReceiver].pkts_received++;
  91. }
  92. /**
  93. * Registers a value of the TCP option Maximum Segment Size (MSS).
  94. * @param ipAddress The IP address which sent the TCP packet.
  95. * @param MSSvalue The MSS value found.
  96. */
  97. void statistics::addMSS(std::string ipAddress, int MSSvalue) {
  98. ip_sumMss[ipAddress] += MSSvalue;
  99. }
  100. /**
  101. * Setter for the timestamp_firstPacket field.
  102. * @param ts The timestamp of the first packet in the PCAP file.
  103. */
  104. void statistics::setTimestampFirstPacket(Tins::Timestamp ts) {
  105. timestamp_firstPacket = ts;
  106. }
  107. /**
  108. * Setter for the timestamp_lastPacket field.
  109. * @param ts The timestamp of the last packet in the PCAP file.
  110. */
  111. void statistics::setTimestampLastPacket(Tins::Timestamp ts) {
  112. timestamp_lastPacket = ts;
  113. }
  114. /**
  115. * Calculates the capture duration.
  116. * @return a formatted string HH:MM:SS.mmmmmm with
  117. * HH: hour, MM: minute, SS: second, mmmmmm: microseconds
  118. */
  119. std::string statistics::getCaptureDurationTimestamp() const {
  120. // Calculate duration
  121. time_t t = (timestamp_lastPacket.seconds() - timestamp_firstPacket.seconds());
  122. time_t ms = (timestamp_lastPacket.microseconds() - timestamp_firstPacket.microseconds());
  123. long int hour = t / 3600;
  124. long int remainder = (t - hour * 3600);
  125. long int minute = remainder / 60;
  126. long int second = (remainder - minute * 60) % 60;
  127. long int microseconds = ms;
  128. // Build desired output format: YYYY-mm-dd hh:mm:ss
  129. char out[64];
  130. sprintf(out, "%02ld:%02ld:%02ld.%06ld ", hour, minute, second, microseconds);
  131. return std::string(out);
  132. }
  133. /**
  134. * Calculates the capture duration.
  135. * @return a formatted string SS.mmmmmm with
  136. * S: seconds (UNIX time), mmmmmm: microseconds
  137. */
  138. float statistics::getCaptureDurationSeconds() const {
  139. timeval d;
  140. d.tv_sec = timestamp_lastPacket.seconds() - timestamp_firstPacket.seconds();
  141. d.tv_usec = timestamp_lastPacket.microseconds() - timestamp_firstPacket.microseconds();
  142. char tmbuf[64], buf[64];
  143. auto nowtm = localtime(&(d.tv_sec));
  144. strftime(tmbuf, sizeof(tmbuf), "%S", nowtm);
  145. snprintf(buf, sizeof(buf), "%s.%06u", tmbuf, (uint) d.tv_usec);
  146. return std::stof(std::string(buf));
  147. }
  148. /**
  149. * Creates a timestamp based on a time_t seconds (UNIX time format) and microseconds.
  150. * @param seconds
  151. * @param microseconds
  152. * @return a formatted string Y-m-d H:M:S.m with
  153. * Y: year, m: month, d: day, H: hour, M: minute, S: second, m: microseconds
  154. */
  155. std::string statistics::getFormattedTimestamp(time_t seconds, suseconds_t microseconds) const {
  156. timeval tv;
  157. tv.tv_sec = seconds;
  158. tv.tv_usec = microseconds;
  159. char tmbuf[64], buf[64];
  160. auto nowtm = localtime(&(tv.tv_sec));
  161. strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%d %H:%M:%S", nowtm);
  162. snprintf(buf, sizeof(buf), "%s.%06u", tmbuf, (uint) tv.tv_usec);
  163. return std::string(buf);
  164. }
  165. /**
  166. * Calculates the statistics for a given IP address.
  167. * @param ipAddress The IP address whose statistics should be calculated.
  168. * @return a ip_stats struct containing statistical data derived by the statistical data collected.
  169. */
  170. ip_stats statistics::getStatsForIP(std::string ipAddress) {
  171. float duration = getCaptureDurationSeconds();
  172. entry_ipStat ipStatEntry = ip_statistics[ipAddress];
  173. ip_stats s;
  174. s.bandwidthKBitsIn = (ipStatEntry.kbytes_received / duration) * 8;
  175. s.bandwidthKBitsOut = (ipStatEntry.kbytes_sent / duration) * 8;
  176. s.packetPerSecondIn = (ipStatEntry.pkts_received / duration);
  177. s.packetPerSecondOut = (ipStatEntry.pkts_sent / duration);
  178. s.AvgPacketSizeSent = (ipStatEntry.kbytes_sent / ipStatEntry.pkts_sent);
  179. s.AvgPacketSizeRecv = (ipStatEntry.kbytes_received / ipStatEntry.pkts_received);
  180. int sumMSS = ip_sumMss[ipAddress];
  181. int tcpPacketsSent = getProtocolCount(ipAddress, "TCP");
  182. s.AvgMaxSegmentSizeTCP = ((sumMSS > 0 && tcpPacketsSent > 0) ? (sumMSS / tcpPacketsSent) : 0);
  183. return s;
  184. }
  185. /**
  186. * Increments the packet counter.
  187. */
  188. void statistics::incrementPacketCount() {
  189. packetCount++;
  190. }
  191. /**
  192. * Prints the statistics of the PCAP and IP specific statistics for the given IP address.
  193. * @param ipAddress The IP address whose statistics should be printed. Can be empty "" to print only general file statistics.
  194. */
  195. void statistics::printStats(std::string ipAddress) {
  196. std::stringstream ss;
  197. ss << std::endl;
  198. ss << "Capture duration: " << getCaptureDurationSeconds() << " seconds" << std::endl;
  199. ss << "Capture duration (HH:MM:SS.mmmmmm): " << getCaptureDurationTimestamp() << std::endl;
  200. ss << "#Packets: " << packetCount << std::endl;
  201. ss << std::endl;
  202. // Print IP address specific statistics only if IP address was given
  203. if (ipAddress != "") {
  204. entry_ipStat e = ip_statistics[ipAddress];
  205. ss << "\n----- STATS FOR IP ADDRESS [" << ipAddress << "] -------" << std::endl;
  206. ss << std::endl << "KBytes sent: " << e.kbytes_sent << std::endl;
  207. ss << "KBytes received: " << e.kbytes_received << std::endl;
  208. ss << "Packets sent: " << e.pkts_sent << std::endl;
  209. ss << "Packets received: " << e.pkts_received << "\n\n";
  210. ip_stats is = getStatsForIP(ipAddress);
  211. ss << "Bandwidth IN: " << is.bandwidthKBitsIn << " kbit/s" << std::endl;
  212. ss << "Bandwidth OUT: " << is.bandwidthKBitsOut << " kbit/s" << std::endl;
  213. ss << "Packets per second IN: " << is.packetPerSecondIn << std::endl;
  214. ss << "Packets per second OUT: " << is.packetPerSecondOut << std::endl;
  215. ss << "Avg Packet Size Sent: " << is.AvgPacketSizeSent << " kbytes" << std::endl;
  216. ss << "Avg Packet Size Received: " << is.AvgPacketSizeRecv << " kbytes" << std::endl;
  217. ss << "Avg MSS: " << is.AvgMaxSegmentSizeTCP << " bytes" << std::endl;
  218. }
  219. std::cout << ss.str();
  220. }
  221. /**
  222. * Derives general PCAP file statistics from the collected statistical data and
  223. * writes all data into a SQLite database, located at database_path.
  224. * @param database_path The path of the SQLite database file ending with .sqlite3.
  225. */
  226. void statistics::writeToDatabase(std::string database_path) {
  227. // Generate general file statistics
  228. float duration = getCaptureDurationSeconds();
  229. long sumPacketsSent = 0, senderCountIP = 0;
  230. float sumBandwidthIn = 0.0, sumBandwidthOut = 0.0;
  231. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  232. sumPacketsSent += i->second.pkts_sent;
  233. // Consumed bandwith (bytes) for sending packets
  234. sumBandwidthIn += (i->second.kbytes_received / duration);
  235. sumBandwidthOut += (i->second.kbytes_sent / duration);
  236. senderCountIP++;
  237. }
  238. float avgPacketRate = (packetCount / duration);
  239. long avgPacketSize = getAvgPacketSize();
  240. long avgPacketsSentPerHost = (sumPacketsSent / senderCountIP);
  241. float avgBandwidthInKBits = (sumBandwidthIn / senderCountIP) * 8;
  242. float avgBandwidthOutInKBits = (sumBandwidthOut / senderCountIP) * 8;
  243. // Create database and write information
  244. statistics_db db(database_path);
  245. db.writeStatisticsFile(packetCount, getCaptureDurationSeconds(),
  246. getFormattedTimestamp(timestamp_firstPacket.seconds(), timestamp_firstPacket.microseconds()),
  247. getFormattedTimestamp(timestamp_lastPacket.seconds(), timestamp_lastPacket.microseconds()),
  248. avgPacketRate, avgPacketSize, avgPacketsSentPerHost, avgBandwidthInKBits,
  249. avgBandwidthOutInKBits);
  250. db.writeStatisticsIP(ip_statistics);
  251. db.writeStatisticsTTL(ttl_distribution);
  252. db.writeStatisticsIpMac(ip_mac_mapping);
  253. db.writeStatisticsMss(ip_sumMss);
  254. db.writeStatisticsPorts(ip_ports);
  255. db.writeStatisticsProtocols(protocol_distribution);
  256. // Aidmar
  257. db.writeStatisticsMss_dist(mss_distribution);
  258. db.writeStatisticsWin(win_distribution);
  259. }
  260. /**
  261. * Returns the average packet size.
  262. * @return a float indicating the average packet size in kbytes.
  263. */
  264. float statistics::getAvgPacketSize() const {
  265. // AvgPktSize = (Sum of all packet sizes / #Packets)
  266. return (sumPacketSize / packetCount) / 1024;
  267. }
  268. /**
  269. * Adds the size of a packet (to be used to calculate the avg. packet size).
  270. * @param packetSize The size of the current packet in bytes.
  271. */
  272. void statistics::addPacketSize(uint32_t packetSize) {
  273. sumPacketSize += ((float) packetSize);
  274. }