statistics.cpp 11 KB

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