/* * This file is a part of Winix * and is not publicly distributed * * Copyright (c) 2012, Tomasz Sowa * All rights reserved. * */ #include #include "ipbancontainer.h" #include "log.h" #include "date/date.h" IPBanContainer::IPBanContainer() { is_ipban_tab_sorted = false; soft_max_size = 100; max_size = 110; } void IPBanContainer::SetMaxSize(size_t soft_size, size_t size) { soft_max_size = soft_size; max_size = size; if( max_size < soft_max_size ) max_size = soft_max_size + 1; ipban_tab.reserve(max_size); sort_helper_tab.reserve(max_size); } // returning a reference to the added (or existed) record IPBan & IPBanContainer::AddIP(int ip) { IPBan * old_ip_ban = FindIP(ip); if( !old_ip_ban ) { IPBan ip_ban; ip_ban.ip = ip; if( ipban_tab.size() >= max_size ) RemoveOldRecords(); ipban_tab.push_back(ip_ban); return ipban_tab.back(); } else { return *old_ip_ban; } } // we need to remove some old records for the size of the container // to be less or equal to soft_max_size void IPBanContainer::RemoveOldRecords() { PrintTab(); size_t to_remove = 0; if( ipban_tab.size() >= soft_max_size ) to_remove = ipban_tab.size() - soft_max_size; if( to_remove > 0 ) { log << log4 << "we are going to remove: " << to_remove << " records" << logend; sort_helper_tab.resize(ipban_tab.size()); for(size_t i=0 ; i 0 ) { log << log4 << "removing record index: " << sort_helper_tab[to_remove] << ", last_used: "; PT::Date date(ipban_tab[sort_helper_tab[to_remove]].last_used); log << date << logend; ipban_tab.erase(ipban_tab.begin() + sort_helper_tab[to_remove]); } log << log4 << "after removing we have: " << logend; PrintTab(); } } void IPBanContainer::PrintTab() { log << log4 << "ipban_tab (size: " << ipban_tab.size() << ")" << logend; for(size_t i=0 ; iipban_tab.size() && index2 < container->ipban_tab.size() ) { IPBan & ip1 = container->ipban_tab[index1]; IPBan & ip2 = container->ipban_tab[index2]; // prefer to select records which do not have WINIX_IPBAN_FLAG_ACTIVE if( ip1.HasFlag(WINIX_IPBAN_FLAG_ACTIVE) != ip2.HasFlag(WINIX_IPBAN_FLAG_ACTIVE) ) { return ip2.HasFlag(WINIX_IPBAN_FLAG_ACTIVE); } return ip1.last_used < ip2.last_used; } return false; } IPBan * IPBanContainer::FindIP(int ip) { // !! IMPROVE ME add binary search if is_ipban_tab_sorted is true for(size_t i=0 ; i