Class, methodes, bot..

dev
mbandic 12 months ago
parent 36fe2f9db8
commit 33550ccc69
  1. 1
      .gitignore
  2. 5
      .vscode/settings.json
  3. 48
      lib/ipban.hpp
  4. 59
      src/ipban.cpp
  5. BIN
      test/test
  6. 10
      test/test.cpp

1
.gitignore vendored

@ -0,0 +1 @@
example

@ -0,0 +1,5 @@
{
"files.associations": {
"*.tcc": "cpp"
}
}

@ -0,0 +1,48 @@
#ifndef IP_BAN
#define IP_BAN
#include <iostream>
#include <vector>
#include <string>
#include <future>
#include <mutex>
#include <time.h>
#include <unistd.h>
using namespace std;
namespace marcelb {
#define BOT_LOOP_TIME 60 // 1 minutes
#define BOT_SLEEP_LOOP_TIME 1 // 1 second
struct _ban {
string ip;
time_t _time;
};
class ipban {
mutex io;
time_t ban_duration; // u sekundama
vector<_ban> banned;
future<void> unban_bot;
bool run_unban_bot = true;
// interface možda bude trebao za ban
bool unban(vector<_ban>::iterator ban_itr);
bool ufw_ban(const string& ip);
bool ufw_unban(const string& ip);
public:
ipban(const uint& _duration); // u minutama?
bool ban(const string& ip);
~ipban();
};
static void sleep_if(const uint& _time, const bool& _condition);
}
#endif

@ -0,0 +1,59 @@
#include "../lib/ipban.hpp"
marcelb::ipban::ipban(const uint& _duration) {
ban_duration = _duration*60;
unban_bot = async(launch::async, [&]() {
while (run_unban_bot) {
sleep_if(BOT_LOOP_TIME, run_unban_bot);
cout << "Sleep" << endl;
io.lock();
for (uint i=0; i<banned.size(); i++) {
if (difftime(time(NULL), banned[i]._time) >= ban_duration) {
unban(banned.begin() + i);
}
}
io.unlock();
}
return;
});
}
marcelb::ipban::~ipban() {
run_unban_bot = false;
unban_bot.get();
for (uint i=0; i<banned.size(); i++) {
unban(banned.begin() + i);
}
}
bool marcelb::ipban::ban(const string& ip) {
ufw_ban(ip);
io.lock();
banned.push_back({ip, time(NULL)});
io.unlock();
}
bool marcelb::ipban::unban(vector<_ban>::iterator ban_itr) {
ufw_unban(ban_itr->ip);
io.lock();
banned.erase(ban_itr);
io.unlock();
}
bool marcelb::ipban::ufw_ban(const string& ip) {
cout << "UFW ban IP: " << ip << endl;
}
bool marcelb::ipban::ufw_unban(const string& ip) {
cout << "UFW unban IP: " << ip << endl;
}
static void marcelb::sleep_if(const uint& _time, const bool& _condition) {
time_t start_time = time(NULL);
do {
sleep(BOT_SLEEP_LOOP_TIME);
} while (difftime(time(NULL), start_time) < _time && _condition);
}

Binary file not shown.

@ -0,0 +1,10 @@
#include "../lib/ipban.hpp"
using namespace marcelb;
int main() {
ipban myban(1);
myban.ban("192.168.2.74");
sleep(80);
return 0;
}
Loading…
Cancel
Save