statistics.cpp 11 KB

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