#include #include #include #include #include #include #include #include #include #include #include "dbms_network_acl_utility.hpp" extern "C" { #include "utils/builtins.h" #include "utils/elog.h" } using namespace std; bool isValidHostnameOrIP(const std::string& input) { // Специальный случай: одиночная звездочка if (input == "*") { return true; } // Шаблон для доменов: wildcard ТОЛЬКО в начале (*.domain.com) const std::regex domain_pattern( R"(^(\*\.)?[^*\.]+(\.[^*\.]+)*$)" ); // Шаблон для корректных IPv4‑адресов (ровно 4 октета 0–255) const std::regex ipv4_pattern( R"(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)" ); // Шаблон для IPv4‑подсетей с wildcard: 1–3 октета + * (например, 192.*, 192.168.*) const std::regex ipv4_wildcard_pattern( R"(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){1,3}\*$)" ); // Шаблон для wildcard в начале IPv4 (например, *.168.0.1) const std::regex ipv4_wildcard_start_pattern( R"(^\*\.((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){1,3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)?$)" ); // Шаблон для hostname без * const std::regex hostname_pattern( R"(^[^*\.]+(\.[^*\.]+)*$)" ); // Проверка: если есть wildcard в конце (но не в начале) — ошибка для доменов if (input.find('*') != std::string::npos) { if (input.back() == '*' && !std::regex_match(input, ipv4_wildcard_pattern)) { return false; // Отклоняем www.example.ten.* и 192.168.0.1.* } } // Oracle DBMS_NETWORK_ACL_UTILITY.DOMAIN_LEVEL rejects CIDR syntax. // Keep this restriction in the DOMAIN_LEVEL validation path only: // EQUALS_HOST and CONTAINS_HOST legitimately accept subnet prefixes. // Проверка: ':' и '/' недопустимы в DOMAIN_LEVEL. if (input.find(':') != std::string::npos || input.find('/') != std::string::npos) { return false; } return std::regex_match(input, domain_pattern) || std::regex_match(input, ipv4_pattern) || std::regex_match(input, ipv4_wildcard_pattern) || std::regex_match(input, ipv4_wildcard_start_pattern) || std::regex_match(input, hostname_pattern); } int countSegments(const std::string& str) { if (str.empty()) return 0; // Считаем количество сегментов int count = 1; for (char c : str) { if (c == '.') count++; } // Проверяем первый сегмент bool firstIsStar = (str[0] == '*'); // Проверяем последний сегмент (только если это не тот же самый сегмент) bool lastIsStar = (str.back() == '*'); if (firstIsStar) count--; if (lastIsStar && str.size() > 1) count--; // Не вычитаем дважды для "*" return count; } //---------------------------------------- std::string normalize_ipv4(const std::string& ip) { std::string result; std::stringstream ss(ip); std::string octet; while (std::getline(ss, octet, '.')) { if (!result.empty()) result += '.'; // Удаляем ведущие нули size_t pos = octet.find_first_not_of('0'); if (pos == std::string::npos) { result += '0'; } else { result += octet.substr(pos); } } return result; } uint32_t ip_to_uint32(const std::string& ip) { std::string normalized = normalize_ipv4(ip); struct in_addr addr; if (inet_pton(AF_INET, normalized.c_str(), &addr) == 1) { return ntohl(addr.s_addr); } return 0; } // uint32_t ip_to_uint32(const std::string& ip) { // struct in_addr addr; // if (inet_pton(AF_INET, ip.c_str(), &addr) == 1) { // return ntohl(addr.s_addr); // } // throw std::invalid_argument("Invalid IPv4 address"); // } struct IPv6Address { uint8_t bytes[16]; bool operator==(const IPv6Address& other) const { return memcmp(bytes, other.bytes, 16) == 0; } }; IPv6Address ipv6_to_bytes(const std::string& ip) { struct in6_addr addr; if (inet_pton(AF_INET6, ip.c_str(), &addr) != 1) { throw std::invalid_argument("Invalid IPv6 address"); } IPv6Address result; memcpy(result.bytes, addr.s6_addr, 16); return result; } // Проверки типов bool is_ipv4(const std::string& str) { std::regex ipv4_pattern( R"(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)" ); return std::regex_match(str, ipv4_pattern); } bool is_ipv4_simple(const std::string& str) { // просто 4 любых числа, разделённых . const std::regex ipv4_simple_pattern(R"(^([0-9]+\.){3}[0-9]+$)"); return std::regex_match(str, ipv4_simple_pattern); } bool is_ipv6(const std::string& str) { struct in6_addr addr; return inet_pton(AF_INET6, str.c_str(), &addr) == 1; } bool equals_ipv6(const std::string& str1, const std::string& str2) { struct in6_addr addr1, addr2; if (inet_pton(AF_INET6, str1.c_str(), &addr1) != 1) return false; if (inet_pton(AF_INET6, str2.c_str(), &addr2) != 1) return false; return memcmp(&addr1, &addr2, sizeof(addr1)) == 0; } bool is_ip_address(const std::string& str) { return is_ipv4(str) || is_ipv6(str); } bool is_ipv4_mapped_ipv6(const std::string& str) { struct in6_addr addr; // Пытаемся распарсить как IPv6 if (inet_pton(AF_INET6, str.c_str(), &addr) != 1) { return false; } // Проверяем, что первые 10 байт равны 0, а 11 и 12 байты равны 0xFF // (в сетевом порядке байт, s6_addr[0]..s6_addr[15]) static const uint8_t zero10[10] = {0}; if (memcmp(addr.s6_addr, zero10, 10) != 0) { return false; } if (addr.s6_addr[10] != 0xff || addr.s6_addr[11] != 0xff) { return false; } return true; } std::string ipv4_from_ipv4_mapped_ipv6(const std::string& str) { struct in6_addr addr; // Пытаемся распарсить как IPv6 if (inet_pton(AF_INET6, str.c_str(), &addr) != 1) { return ""; // невалидный IPv6 адрес } // Извлекаем IPv4 (последние 4 байта, хранятся в сетевом порядке) uint32_t ipv4_net; memcpy(&ipv4_net, &addr.s6_addr[12], 4); // Преобразуем в строку struct in_addr ipv4_addr; ipv4_addr.s_addr = ipv4_net; char buf[INET_ADDRSTRLEN]; if (inet_ntop(AF_INET, &ipv4_addr, buf, sizeof(buf)) == nullptr) { return ""; } return std::string(buf); } bool is_cidr_subnet(const std::string& str) { std::regex cidr_pattern( R"(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/([0-9]|[1-2][0-9]|3[0-2])$)" ); return std::regex_match(str, cidr_pattern); } bool is_ipv4_mapped_ipv6_subnet(const std::string& subnet) { size_t slash_pos = subnet.find('/'); if (slash_pos == std::string::npos) return false; std::string ip_part = subnet.substr(0, slash_pos); struct in6_addr addr; if (inet_pton(AF_INET6, ip_part.c_str(), &addr) != 1) { return false; } // Проверяем, что это IPv4-mapped: первые 10 байт нули, 11 и 12 — 0xFF static const uint8_t zero10[10] = {0}; if (memcmp(addr.s6_addr, zero10, 10) != 0) { return false; } return addr.s6_addr[10] == 0xff && addr.s6_addr[11] == 0xff; } bool is_ipv6_cidr(const std::string& str) { size_t slash_pos = str.find('/'); if (slash_pos == std::string::npos) return false; std::string ip_part = str.substr(0, slash_pos); std::string prefix_part = str.substr(slash_pos + 1); // Проверяем префикс: число от 0 до 128 if (prefix_part.empty()) return false; char* endptr; long prefix = strtol(prefix_part.c_str(), &endptr, 10); if (*endptr != '\0' || prefix < 0 || prefix > 128) return false; // Проверяем IP-часть через inet_pton struct in6_addr addr; return inet_pton(AF_INET6, ip_part.c_str(), &addr) == 1; } bool is_wildcard_subnet(const std::string& str) { std::regex wildcard_pattern( R"(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){1,3}\*$)" ); return std::regex_match(str, wildcard_pattern); } bool is_wildcard_subnet_simple(const std::string& str) { // Шаблон: от 1 до 3 групп цифр, разделённых точками, затем .* static const std::regex pattern(R"(^[0-9]+(\.[0-9]+){0,2}\.\*$)"); return std::regex_match(str, pattern); } bool is_subnet(const std::string& str) { return is_wildcard_subnet(str) || is_cidr_subnet(str) || is_ipv6_cidr(str); } bool is_ipv4_wildcard_start(const std::string& str) { std::regex pattern( R"(^\*\.((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){1,3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)?$)" ); return std::regex_match(str, pattern); } bool is_domain_with_wildcard(const std::string& str) { return str.size() >= 2 && str[0] == '*' && str[1] == '.' /*&& !is_ipv4_wildcard_start(str)*/; } bool is_hostname(const std::string& str) { if (str.empty()) return false; if (str == "*") return false; if (is_ip_address(str)) return false; if (is_subnet(str)) return false; if (is_domain_with_wildcard(str)) return false; std::regex hostname_pattern( //R"(^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$)" R"(^[^*\.]+(\.[^*\.]+)*$)" ); return std::regex_match(str, hostname_pattern); } // Вспомогательные функции bool ends_with(const std::string& host, const std::string& domain) { if (domain.size() > host.size()) return false; return host.compare(host.size() - domain.size(), domain.size(), domain) == 0; } bool matches_wildcard_domain(const std::string& host, const std::string& wildcard_domain) { if (!is_domain_with_wildcard(wildcard_domain)) return false; std::string domain_part = wildcard_domain.substr(2); if (!ends_with(host, domain_part)) return false; std::string host_prefix = host.substr(0, host.size() - domain_part.size()); if (host_prefix.empty()) return false; return true; } bool matches_ipv4_cidr(const std::string& host, const std::string& cidr) { size_t slash_pos = cidr.find('/'); if (slash_pos == std::string::npos) return false; std::string subnet_ip = cidr.substr(0, slash_pos); int prefix_len = std::stoi(cidr.substr(slash_pos + 1)); if (!is_ipv4(host) || !is_ipv4(subnet_ip)) return false; uint32_t host_int = ip_to_uint32(host); uint32_t subnet_int = ip_to_uint32(subnet_ip); uint32_t mask = (prefix_len == 0) ? 0 : (~0U) << (32 - prefix_len); return (host_int & mask) == (subnet_int & mask); } bool equals_ipv4_cidr_subnet(const std::string& subnet1, const std::string& subnet2) { // Проверяем наличие '/' size_t slash1 = subnet1.find('/'); size_t slash2 = subnet2.find('/'); if (slash1 == std::string::npos || slash2 == std::string::npos) { return false; } // Извлекаем маски int prefix_len1 = std::stoi(subnet1.substr(slash1 + 1)); int prefix_len2 = std::stoi(subnet2.substr(slash2 + 1)); if (prefix_len1 != prefix_len2) { return false; // разные маски -> разные подсети } // Берём IP-адрес из первой подсети std::string ip1 = subnet1.substr(0, slash1); // Проверяем вхождение ip1 в подсеть subnet2 return matches_ipv4_cidr(ip1, subnet2); } bool matches_ipv6_cidr(const std::string& host, const std::string& cidr) { size_t slash_pos = cidr.find('/'); if (slash_pos == std::string::npos) return false; std::string subnet_ip = cidr.substr(0, slash_pos); int prefix_len = std::stoi(cidr.substr(slash_pos + 1)); IPv6Address subnet_bytes = ipv6_to_bytes(subnet_ip); IPv6Address host_bytes; // Если host - IPv4, преобразуем в IPv4-mapped IPv6 if (is_ipv4(host)) { memset(host_bytes.bytes, 0, 16); host_bytes.bytes[10] = 0xff; host_bytes.bytes[11] = 0xff; struct in_addr addr4; if (inet_pton(AF_INET, host.c_str(), &addr4) != 1) return false; // Копируем сетевой порядок напрямую memcpy(&host_bytes.bytes[12], &addr4.s_addr, 4); } // Если host уже IPv6 else if (is_ipv6(host)) { host_bytes = ipv6_to_bytes(host); } else { return false; } // Проверка префикса int full_bytes = prefix_len / 8; int remaining_bits = prefix_len % 8; for (int i = 0; i < full_bytes; i++) { if (host_bytes.bytes[i] != subnet_bytes.bytes[i]) return false; } if (remaining_bits > 0) { uint8_t mask = (~0U) << (8 - remaining_bits); if ((host_bytes.bytes[full_bytes] & mask) != (subnet_bytes.bytes[full_bytes] & mask)) { return false; } } return true; } bool matches_wildcard_subnet(const std::string& host, const std::string& wildcard) { if (!is_wildcard_subnet(wildcard)) return false; std::vector host_octets; std::vector wildcard_octets; std::stringstream host_ss(host); std::stringstream wildcard_ss(wildcard); std::string octet; while (std::getline(host_ss, octet, '.')) { host_octets.push_back(octet); } while (std::getline(wildcard_ss, octet, '.')) { if (octet == "*") break; wildcard_octets.push_back(octet); } if (host_octets.size() < wildcard_octets.size()) return false; for (size_t i = 0; i < wildcard_octets.size(); i++) { if (host_octets[i] != wildcard_octets[i]) return false; } return true; } bool matches_subnet(const std::string& host, const std::string& subnet) { if (is_cidr_subnet(subnet)) { return matches_ipv4_cidr(host, subnet); } if (is_ipv6_cidr(subnet)) { return matches_ipv6_cidr(host, subnet); } if (is_wildcard_subnet(subnet)) { return matches_wildcard_subnet(host, subnet); } return false; } bool matches_exact_ip(const std::string& host, const std::string& ip) { return is_ip_address(ip) && host == ip; } bool equals_ipv6_cidr(const std::string& subnet1, const std::string& subnet2) { // Извлекаем длины префиксов size_t slash1 = subnet1.find('/'); size_t slash2 = subnet2.find('/'); if (slash1 == std::string::npos || slash2 == std::string::npos) { return false; } int prefix1 = std::stoi(subnet1.substr(slash1 + 1)); int prefix2 = std::stoi(subnet2.substr(slash2 + 1)); if (prefix1 != prefix2) { return false; // разные маски – заведомо разные подсети } // Берём IP-адрес из первой подсети (может быть с ненулевой хостовой частью) std::string ip1 = subnet1.substr(0, slash1); // Проверяем, принадлежит ли этот адрес второй подсети // При равенстве масок это эквивалентно совпадению сетевых адресов return matches_ipv6_cidr(ip1, subnet2); } bool equalsIgnoreCase(const std::string& a, const std::string& b) { if (a.size() != b.size()) return false; return std::equal(a.begin(), a.end(), b.begin(), [](char c1, char c2) { return std::tolower(static_cast(c1)) == std::tolower(static_cast(c2)); }); } int domain_level(const std::string& host, Oid collation) { Numeric res; int32 result; text *host_text = cstring_to_text(host.c_str()); PG_TRY(); { res = DatumGetNumeric(DirectFunctionCall1Coll(dbms_network_acl_utility_domain_level, collation, PointerGetDatum(host_text))); result = DatumGetInt32(DirectFunctionCall1(numeric_int4, NumericGetDatum(res))); } PG_CATCH(); { pfree(host_text); PG_RE_THROW(); } PG_END_TRY(); pfree(host_text); return result; } int contains_host(const std::string& host, const std::string& domain, Oid coll) { // Случай 4: domain = "*" -> возвращает 0 if (domain == "*") { return 0; } // Случай 3: domain - IP адрес или подсеть if (is_ip_address(domain)) { if (matches_exact_ip(host, domain)) { // Для точного IP возвращаем количество октетов (4 или 8), а не биты if(is_ipv4(domain)) return 32; else { if(is_ipv4_mapped_ipv6(domain)) return 32; return 128; } } return -1; } if (is_subnet(domain)) { if (matches_subnet(host, domain)) { // Для подсети возвращаем количество значимых бит (как в Oracle) // хост ipv4 а domain ipv4mappedipv6 if (is_ipv4(host) && is_ipv4_mapped_ipv6_subnet(domain)) { if (matches_ipv6_cidr(host, domain)) { size_t slash_pos = domain.find('/'); return std::stoi(domain.substr(slash_pos + 1)) - 96; // 120 - 96 = 24 } } if (is_cidr_subnet(domain)) { size_t slash_pos = domain.find('/'); return std::stoi(domain.substr(slash_pos + 1)); } if (is_ipv6_cidr(domain)) { size_t slash_pos = domain.find('/'); return std::stoi(domain.substr(slash_pos + 1)); } if (is_wildcard_subnet(domain)) { int significant_octets = 0; std::stringstream ss(domain); std::string octet; while (std::getline(ss, octet, '.')) { if (octet == "*") break; significant_octets++; } return significant_octets * 8; } } //return -1; } // Случай 2: domain - доменное имя с wildcard if (is_domain_with_wildcard(domain)) { if (matches_wildcard_domain(host, domain)) { int res; PG_TRY(); { res = domain_level(domain, coll); } PG_CATCH(); { res = -1; } PG_END_TRY(); return res; } return -1; } // Случай 1: domain - hostname if (is_hostname(domain)) { // Проверка на точное совпадение if (host == domain) { int res; PG_TRY(); { res = domain_level(domain, coll); } PG_CATCH(); { res = -1; } PG_END_TRY(); return res; } // Проверка на вхождение (поддомен) if (ends_with(host, "." + domain)) { int res; PG_TRY(); { res = domain_level(domain, coll)+1; } PG_CATCH(); { res = -1; } PG_END_TRY(); return res; } return -1; } return -1; } std::list domains(const std::string& input) { std::list result; // Запрещённые символы if (input.find(':') != std::string::npos || input.find('/') != std::string::npos) { return result; // пустой список } // Пустые сегменты при разбиении по точке if (input.empty() || input.front() == '.' || input.back() == '.') { return result; } if (input.find("..") != std::string::npos) { return result; } // Случай одиночной звёздочки if (input == "*") { result.push_back("*"); return result; } // 1. Обработка IPv4-адреса (без звёздочек) if (is_ipv4_simple(input)) { std::vector octets; std::stringstream ss(input); std::string octet; while (std::getline(ss, octet, '.')) { octets.push_back(octet); } // octets.size() должно быть 4 for (size_t i = 0; i <= octets.size(); ++i) { if (i == 0) { result.push_back(input); // точный адрес } else if (i < octets.size()) { std::string pattern; for (size_t j = 0; j < octets.size() - i; ++j) { if (j > 0) pattern += "."; pattern += octets[j]; } pattern += ".*"; result.push_back(pattern); } else { // i == octets.size() result.push_back("*"); } } return result; } // 2. Обработка wildcard-подсети вида "192.168.*" (звёздочка только в конце) if (is_wildcard_subnet_simple(input)) { std::vector parts; std::stringstream ss(input); std::string part; while (std::getline(ss, part, '.')) { parts.push_back(part); } // Ожидаем, что последний элемент – "*" if (parts.empty() || parts.back() != "*") { return result; // некорректный формат – возвращаем пустой список } int n = static_cast(parts.size()) - 1; // количество значащих октетов for (int i = n; i >= 0; --i) { if (i == n) { result.push_back(input); // исходная подсеть } else if (i > 0) { std::string pattern; for (int j = 0; j < i; ++j) { if (j > 0) pattern += "."; pattern += parts[j]; } pattern += ".*"; result.push_back(pattern); } else { // i == 0 result.push_back("*"); } } return result; } // 3. Обработка доменного имени с wildcard в начале (например, "*.example.com") if (is_domain_with_wildcard(input)) { // Формат: "*." + остаток std::string rest = input.substr(2); // всё после "*." std::vector components; std::stringstream ss(rest); std::string comp; while (std::getline(ss, comp, '.')) { // * допустима только в 1 сегменте if(comp.find("*")!= std::string::npos){ return result; } components.push_back(comp); } int n = static_cast(components.size()); // Исходный шаблон result.push_back(input); // Генерация более коротких шаблонов: "*." + суффикс из последних i компонентов for (int i = n - 1; i >= 1; --i) { std::string suffix; for (int j = n - i; j < n; ++j) { if (!suffix.empty()) suffix += "."; suffix += components[j]; } result.push_back("*." + suffix); } // Самый общий шаблон result.push_back("*"); return result; } // 4. Обычное доменное имя (без звёздочек, не IPv4) { std::vector components; std::stringstream ss(input); std::string comp; int cnt = 0; while (std::getline(ss, comp, '.')) { // * допустима только в 1 сегменте if(cnt>0) { if(comp.find("*")!= std::string::npos){ return result; } } ++cnt; components.push_back(comp); } int k = static_cast(components.size()); for (int i = 0; i <= k; ++i) { if (i == 0) { result.push_back(input); // точное имя } else if (i < k) { std::string pattern = "*."; for (int j = i; j < k; ++j) { if (j > i) pattern += "."; pattern += components[j]; } result.push_back(pattern); } else { // i == k result.push_back("*"); } } return result; } } // Canonical IPv4 network for the EQUALS_HOST cross-notation comparison. // Accept valid IPv4 CIDR, contiguous wildcard IPv4 prefix, or mapped IPv6 CIDR // with a prefix of at least 96 bits. Other inputs use existing semantics. struct ACLIPv4Network { uint32_t network; int prefix; }; static bool acl_parse_ipv4_network(const std::string& input, ACLIPv4Network& out) { std::string address; int prefix = -1; if (is_cidr_subnet(input)) { const size_t slash = input.find('/'); address = input.substr(0, slash); prefix = std::stoi(input.substr(slash + 1)); } else if (is_wildcard_subnet(input)) { const size_t star = input.find('*'); const std::string digits = input.substr(0, star); int octets = 0; for (char c : digits) if (c == '.') ++octets; // The trailing period precedes '*'; number of prefix octets == dots. prefix = octets * 8; address = digits; for (int i = octets; i < 4; ++i) address += (i == octets ? "0" : ".0"); // digits ends in '.', and the first zero is appended directly. } else if (is_ipv6_cidr(input) && is_ipv4_mapped_ipv6_subnet(input)) { const size_t slash = input.find('/'); const int mapped_prefix = std::stoi(input.substr(slash + 1)); if (mapped_prefix < 96) return false; address = ipv4_from_ipv4_mapped_ipv6(input.substr(0, slash)); prefix = mapped_prefix - 96; } else { return false; } if (prefix < 0 || prefix > 32 || !is_ipv4(address)) return false; const uint32_t mask = (prefix == 0) ? 0U : (~0U << (32 - prefix)); out.network = ip_to_uint32(address) & mask; out.prefix = prefix; return true; } int32 equals_host(const string &host1, const string &host2){ // Normalize only cross-notation subnet comparison; preserve established // behavior for same-notation inputs, including invalid wildcard strings. ACLIPv4Network net1, net2; const bool wildcard1 = is_wildcard_subnet(host1); const bool wildcard2 = is_wildcard_subnet(host2); const bool cidr4_1 = is_cidr_subnet(host1); const bool cidr4_2 = is_cidr_subnet(host2); const bool mapped1 = is_ipv6_cidr(host1) && is_ipv4_mapped_ipv6_subnet(host1); const bool mapped2 = is_ipv6_cidr(host2) && is_ipv4_mapped_ipv6_subnet(host2); if (((wildcard1 && (cidr4_2 || mapped2)) || (wildcard2 && (cidr4_1 || mapped1)) || (cidr4_1 && mapped2) || (cidr4_2 && mapped1)) && acl_parse_ipv4_network(host1, net1) && acl_parse_ipv4_network(host2, net2)) return net1.prefix == net2.prefix && net1.network == net2.network ? 1 : 0; // ipv4 if(is_ipv4(host1) && is_ipv4(host2)){ if(ip_to_uint32(host1)==ip_to_uint32(host2)){ return 1; } return 0; } // ipv4 cidr if(is_cidr_subnet(host1) && is_cidr_subnet(host2)){ return equals_ipv4_cidr_subnet(host1, host2); } // ipv4 subnet * if (is_wildcard_subnet_simple(host1) && is_wildcard_subnet_simple(host2)) { } // host1 ipv4 host2 ipv4 mapped ipv6 if (is_ipv4(host1) && is_ipv4_mapped_ipv6(host2)) { string ip1 = normalize_ipv4(host1); string ip2 = ipv4_from_ipv4_mapped_ipv6(host2); if(ip1==ip2) return 1; return 0; } // host2 ipv4 host1 ipv4 mapped ipv6 if (is_ipv4(host2) && is_ipv4_mapped_ipv6(host1)) { string ip1 = normalize_ipv4(host2); string ip2 = ipv4_from_ipv4_mapped_ipv6(host1); if(ip1==ip2) return 1; return 0; } if(is_ipv6(host1) && is_ipv6(host2)) { if(equals_ipv6(host1, host2)) return 1; return 0; } if(is_ipv6_cidr(host1) && is_ipv6_cidr(host2)){ if(equals_ipv6_cidr(host1, host2)){ return 1; } return 0; } // для остальных случаев - сравнение без учёта регистра if(equalsIgnoreCase(host1, host2)) return 1; return 0; } extern "C" { PG_FUNCTION_INFO_V1(dbms_network_acl_utility_contains_host); PG_FUNCTION_INFO_V1(dbms_network_acl_utility_domains); PG_FUNCTION_INFO_V1(dbms_network_acl_utility_domain_level); PG_FUNCTION_INFO_V1(dbms_network_acl_utility_equals_host); /** * @brief проверяет, содержится ли указанный узел в заданном домене или подсети * @details функция определяет, содержится ли указанный узел в заданном домене или подсети, учитывая различные форматы представления IP-адресов (например, IPv4-отображенные IPv6-адреса) * * Parameters: * * @param HOST (in) VARCHAR2: Сетевой узел * * @param DOMAIN (in) VARCHAR2: Домен или подсеть * * * * * * @see https://docs.oracle.com/en/database/oracle/oracle-database/23/arpls/DBMS_NETWORK_ACL_UTILITY.html */ Datum dbms_network_acl_utility_contains_host(PG_FUNCTION_ARGS) { Numeric result; int32 res = 0; if(PG_ARGISNULL(0) || PG_ARGISNULL(1)){ PG_RETURN_NULL(); } text *host = PG_GETARG_TEXT_PP(0); text *domain = PG_GETARG_TEXT_PP(1); char *host_str = text_to_cstring(host); char *domain_str = text_to_cstring(domain); res = contains_host(std::string(host_str), std::string(domain_str), PG_GET_COLLATION()); if(res<0){ PG_RETURN_NULL(); } result = DatumGetNumeric(DirectFunctionCall1(int4_numeric, Int32GetDatum(res))); PG_RETURN_NUMERIC(result); } /** * @brief возвращает домены/подсети, ACL которых определяют доступ к указанному узлу * @details функция возвращает домены или подсети, списки контроля доступа (ACL) которых определяют права пользователей на доступ к указанному узлу * * Parameters: * * @param HOST (in) VARCHAR2: Сетевой узел * * * * * * @see https://docs.oracle.com/en/database/oracle/oracle-database/23/arpls/DBMS_NETWORK_ACL_UTILITY.html */ Datum dbms_network_acl_utility_domains(PG_FUNCTION_ARGS) { text *host = PG_ARGISNULL(0) ? NULL : PG_GETARG_TEXT_PP(0); if(PG_ARGISNULL(0)){ ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ORA-24244: invalid host or port for access control list (ACL) assignment"))); } char *host_str = text_to_cstring(host); list domains_lst = domains(string(host_str)); if(domains_lst.empty()){ pfree(host_str); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ORA-24244: invalid host or port for access control list (ACL) assignment"))); } else { ereport(NOTICE, (errmsg("DOMAINS:"))); } for(string el : domains_lst){ ereport(NOTICE, (errmsg("%s", el.c_str()))); } ereport(NOTICE, (errmsg("Функция dbms_network_acl_utility.domains еще не реализована."))); pfree(host_str); PG_RETURN_VOID(); } /** * @brief определяет уровень домена для указанного узла/домена * @details функция возвращает уровень домена (количество точек в FQDN) для указанного сетевого узла, домена или подсети * * Parameters: * * @param HOST (in) VARCHAR2: Сетевой узел или домен * * * * * * @see https://docs.oracle.com/en/database/oracle/oracle-database/23/arpls/DBMS_NETWORK_ACL_UTILITY.html */ Datum dbms_network_acl_utility_domain_level(PG_FUNCTION_ARGS) { Numeric result; int32 res; if(PG_ARGISNULL(0)){ ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ORA-24244: invalid host or port for access control list (ACL) assignment"))); } text *host = PG_GETARG_TEXT_PP(0); char *host_str = text_to_cstring(host); std::string host_string(host_str); if(!isValidHostnameOrIP(host_string)){ pfree(host_str); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ORA-24244: invalid host or port for access control list (ACL) assignment"))); } res = countSegments(host_string); result = DatumGetNumeric(DirectFunctionCall1(int4_numeric, Int32GetDatum(res))); pfree(host_str); PG_RETURN_NUMERIC(result); } /** * @brief сравнивает два сетевых узла/домена на идентичность * @details функция определяет, представляют ли два указанных узла/домена одно и то же сетевое расположение, учитывая различные форматы IP-адресов * * Parameters: * * @param HOST1 (in) VARCHAR2: Первый сетевой узел * * @param HOST2 (in) VARCHAR2: Второй сетевой узел * * * * * * @see https://docs.oracle.com/en/database/oracle/oracle-database/23/arpls/DBMS_NETWORK_ACL_UTILITY.html */ Datum dbms_network_acl_utility_equals_host(PG_FUNCTION_ARGS) { Numeric result; int32 res = 0; if(PG_ARGISNULL(0) || PG_ARGISNULL(1)){ PG_RETURN_NULL(); } text *host1 = PG_GETARG_TEXT_PP(0); text *host2 = PG_GETARG_TEXT_PP(1); char *host1_str = text_to_cstring(host1); char *host2_str = text_to_cstring(host2); res = equals_host(string(host1_str), string(host2_str)); pfree(host1_str); pfree(host2_str); result = DatumGetNumeric(DirectFunctionCall1(int4_numeric, Int32GetDatum(res))); PG_RETURN_NUMERIC(result); } } // extern "C"