File indexing completed on 2024-06-23 05:27:53

0001 /*
0002     SPDX-FileCopyrightText: 2019 Arjen Hiemstra <ahiemstra@heimr.nl>
0003 
0004     SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0005 */
0006 
0007 #ifndef CONNECTIONMAPPING_H
0008 #define CONNECTIONMAPPING_H
0009 
0010 #include <atomic>
0011 #include <mutex>
0012 #include <regex>
0013 #include <thread>
0014 #include <unordered_map>
0015 #include <unordered_set>
0016 
0017 #include <netlink/socket.h>
0018 
0019 #include "Packet.h"
0020 
0021 struct nl_msg;
0022 
0023 /**
0024  * @todo write docs
0025  */
0026 class ConnectionMapping
0027 {
0028 public:
0029     using inode_t = uint32_t;
0030     using pid_t = int;
0031 
0032     struct PacketResult {
0033         pid_t pid = 0;
0034         Packet::Direction direction;
0035     };
0036 
0037     ConnectionMapping();
0038     ~ConnectionMapping();
0039 
0040     PacketResult pidForPacket(const Packet &packet);
0041 
0042 private:
0043     struct State {
0044         State &operator=(const State &other)
0045         {
0046             addressToInode = other.addressToInode;
0047             inodeToPid = other.inodeToPid;
0048 
0049             return *this;
0050         }
0051 
0052         std::unordered_map<Packet::Address, inode_t> addressToInode;
0053         std::unordered_map<inode_t, pid_t> inodeToPid;
0054     };
0055 
0056     void loop();
0057     bool dumpSockets(nl_sock *socket);
0058     bool dumpSockets(nl_sock *socket, int inet_family, int protocol);
0059     void parsePid();
0060 
0061     State m_oldState;
0062     State m_newState;
0063 
0064     bool m_newInode = false;
0065     std::unordered_set<Packet::Address> m_seenAddresses;
0066     std::unordered_set<inode_t> m_seenInodes;
0067 
0068     std::thread m_thread;
0069     std::atomic_bool m_running;
0070     std::mutex m_mutex;
0071 
0072     friend int parseInetDiagMesg(struct nl_msg *msg, void *arg);
0073 };
0074 
0075 #endif // CONNECTIONMAPPING_H