statistics.cpp 11 KB

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