#include "utl_inaddr.hpp"
|
|
extern "C" {
|
#include "utils/builtins.h"
|
#include "utils/elog.h"
|
#include "utils/varlena.h"
|
#include "varatt.h"
|
}
|
|
#include <string>
|
#include <vector>
|
#include <stdexcept>
|
#include <cstring>
|
|
#include <sys/types.h>
|
#include <sys/socket.h>
|
#include <netdb.h>
|
#include <arpa/inet.h>
|
#include <unistd.h>
|
|
namespace {
|
|
[[noreturn]] void raise_unknown_host(const char* what) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("ORA-29257: UNKNOWN_HOST: %s", (what && *what) ? what : "host/ip")));
|
__builtin_unreachable();
|
}
|
|
static std::string cstr_or_empty(text* t) {
|
if (!t) return {};
|
return std::string(VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
|
}
|
|
static std::string strip_domain(const std::string& fq) {
|
auto p = fq.find('.');
|
return (p == std::string::npos) ? fq : fq.substr(0, p);
|
}
|
|
static bool sockaddr_is_loopback(const sockaddr* sa) {
|
if (!sa) return false;
|
if (sa->sa_family == AF_INET) {
|
auto a = reinterpret_cast<const sockaddr_in*>(sa)->sin_addr.s_addr;
|
// 127.0.0.0/8
|
return (ntohl(a) >> 24) == 127;
|
} else if (sa->sa_family == AF_INET6) {
|
const uint8_t* b = reinterpret_cast<const uint8_t*>(
|
&reinterpret_cast<const sockaddr_in6*>(sa)->sin6_addr);
|
// ::1
|
for (int i = 0; i < 15; ++i) if (b[i] != 0) return false;
|
return b[15] == 1;
|
}
|
return false;
|
}
|
|
static std::string sockaddr_to_ip(const sockaddr* sa, socklen_t len) {
|
char buf[NI_MAXHOST] = {0};
|
int rc = getnameinfo(sa, len, buf, sizeof(buf), nullptr, 0, NI_NUMERICHOST);
|
if (rc != 0) throw std::runtime_error(gai_strerror(rc));
|
return std::string(buf);
|
}
|
|
static bool parse_ip(const std::string& s, sockaddr_storage& ss, socklen_t& slen) {
|
memset(&ss, 0, sizeof(ss));
|
sockaddr_in sa4{}; sockaddr_in6 sa6{};
|
if (inet_pton(AF_INET, s.c_str(), &sa4.sin_addr) == 1) {
|
sa4.sin_family = AF_INET;
|
memcpy(&ss, &sa4, sizeof(sa4));
|
slen = sizeof(sockaddr_in);
|
return true;
|
}
|
if (inet_pton(AF_INET6, s.c_str(), &sa6.sin6_addr) == 1) {
|
sa6.sin6_family = AF_INET6;
|
memcpy(&ss, &sa6, sizeof(sa6));
|
slen = sizeof(sockaddr_in6);
|
return true;
|
}
|
return false;
|
}
|
|
static std::string pick_best_ip(struct addrinfo* ai) {
|
// 1) IPv4 non-loopback; 2) any IPv4; 3) IPv6 non-loopback; 4) первое, что есть.
|
struct addrinfo* first = ai;
|
for (auto p = ai; p; p = p->ai_next)
|
if (p->ai_family == AF_INET && !sockaddr_is_loopback(p->ai_addr))
|
return sockaddr_to_ip(p->ai_addr, p->ai_addrlen);
|
for (auto p = ai; p; p = p->ai_next)
|
if (p->ai_family == AF_INET)
|
return sockaddr_to_ip(p->ai_addr, p->ai_addrlen);
|
for (auto p = ai; p; p = p->ai_next)
|
if (p->ai_family == AF_INET6 && !sockaddr_is_loopback(p->ai_addr))
|
return sockaddr_to_ip(p->ai_addr, p->ai_addrlen);
|
if (first)
|
return sockaddr_to_ip(first->ai_addr, first->ai_addrlen);
|
// ничего
|
return {};
|
}
|
|
static std::string resolve_hostname_to_ip(const std::string& host) {
|
struct addrinfo hints{}; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM;
|
struct addrinfo* res = nullptr;
|
int rc = getaddrinfo(host.c_str(), nullptr, &hints, &res);
|
if (rc != 0 || !res) {
|
raise_unknown_host(host.c_str());
|
}
|
std::string out;
|
try {
|
out = pick_best_ip(res);
|
} catch (...) {
|
freeaddrinfo(res);
|
throw;
|
}
|
freeaddrinfo(res);
|
if (out.empty())
|
raise_unknown_host(host.c_str());
|
return out;
|
}
|
|
static std::string get_local_hostname_short() {
|
char buf[NI_MAXHOST] = {0};
|
if (gethostname(buf, sizeof(buf)) != 0 || !*buf) {
|
// fallback
|
return "localhost";
|
}
|
return strip_domain(std::string(buf));
|
}
|
|
static std::string reverse_ip_to_name(const std::string& ip) {
|
sockaddr_storage ss{}; socklen_t slen = 0;
|
if (!parse_ip(ip, ss, slen))
|
raise_unknown_host(ip.c_str());
|
char host[NI_MAXHOST] = {0};
|
int rc = getnameinfo(reinterpret_cast<sockaddr*>(&ss), slen,
|
host, sizeof(host), nullptr, 0, NI_NAMEREQD);
|
if (rc != 0 || !*host)
|
raise_unknown_host(ip.c_str());
|
return std::string(host); // FQDN по возможности
|
}
|
|
} // anon namespace
|
|
extern "C" {
|
|
PG_FUNCTION_INFO_V1(utl_inaddr_get_host_address);
|
PG_FUNCTION_INFO_V1(utl_inaddr_get_host_name);
|
PG_FUNCTION_INFO_V1(utl_inaddr_get_local_ip);
|
|
PG_FUNCTION_INFO_V1(utl_inaddr_get_version);
|
|
/// @brief Версия RUDB пакета UTL_INADDR (Oracle UTL_INADDR пакет)
|
#define RUDB_UTL_INADDR_VERSION "1.0.0"
|
|
/*
|
* @qdb_func: utl_inaddr_get_host_address(text)
|
* @ora_func: UTL_INADDR.GET_HOST_ADDRESS(VARCHAR2)
|
*/
|
Datum utl_inaddr_get_host_address(PG_FUNCTION_ARGS)
|
{
|
try {
|
std::string arg;
|
if (PG_NARGS() >= 1 && !PG_ARGISNULL(0)) {
|
arg = cstr_or_empty(PG_GETARG_TEXT_PP(0));
|
// Пустая строка трактуем как NULL по духу Oracle
|
if (arg.empty()) arg = {};
|
}
|
|
std::string ip;
|
if (arg.empty()) {
|
// локальный IP
|
ip = TextDatumGetCString(DirectFunctionCall0(utl_inaddr_get_local_ip));
|
} else {
|
// если уже IP — вернуть нормализованный, иначе резолв имени
|
sockaddr_storage ss{}; socklen_t slen = 0;
|
if (parse_ip(arg, ss, slen)) {
|
ip = sockaddr_to_ip(reinterpret_cast<sockaddr*>(&ss), slen);
|
} else {
|
ip = resolve_hostname_to_ip(arg);
|
}
|
}
|
text* out = cstring_to_text(ip.c_str());
|
PG_RETURN_TEXT_P(out);
|
} catch (const std::exception& e) {
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("UTL_INADDR.GET_HOST_ADDRESS: %s", e.what())));
|
}
|
PG_RETURN_NULL(); // недостижимо
|
}
|
|
/*
|
* @qdb_func: utl_inaddr_get_host_name(text)
|
* @ora_func: UTL_INADDR.GET_HOST_NAME(VARCHAR2)
|
*/
|
Datum utl_inaddr_get_host_name(PG_FUNCTION_ARGS)
|
{
|
try {
|
std::string arg;
|
if (PG_NARGS() >= 1 && !PG_ARGISNULL(0)) {
|
arg = cstr_or_empty(PG_GETARG_TEXT_PP(0));
|
if (arg.empty()) arg = {};
|
}
|
|
std::string name;
|
if (arg.empty()) {
|
// локальное короткое имя без домена
|
name = get_local_hostname_short();
|
} else {
|
// обратная зона: FQDN
|
name = reverse_ip_to_name(arg);
|
}
|
text* out = cstring_to_text(name.c_str());
|
PG_RETURN_TEXT_P(out);
|
} catch (const std::exception& e) {
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("UTL_INADDR.GET_HOST_NAME: %s", e.what())));
|
}
|
PG_RETURN_NULL();
|
}
|
|
Datum utl_inaddr_get_local_ip(PG_FUNCTION_ARGS) {
|
// пробуем по hostname → A/AAAA
|
std::string h = get_local_hostname_short();
|
struct addrinfo hints{}; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM;
|
struct addrinfo* res = nullptr;
|
int rc = getaddrinfo(h.c_str(), nullptr, &hints, &res);
|
if (rc == 0 && res) {
|
std::string out;
|
try { out = pick_best_ip(res); }
|
catch (...) { freeaddrinfo(res); throw; }
|
freeaddrinfo(res);
|
if (!out.empty()) PG_RETURN_TEXT_P(cstring_to_text(out.c_str()));
|
}
|
// fallback 127.0.0.1
|
PG_RETURN_TEXT_P(cstring_to_text("127.0.0.1"));
|
}
|
|
/// @brief Возвращает версию RUDB пакета UTL_INADDR (Oracle UTL_INADDR пакет)
|
Datum utl_inaddr_get_version(PG_FUNCTION_ARGS) {
|
PG_RETURN_TEXT_P(cstring_to_text(RUDB_UTL_INADDR_VERSION));
|
}
|
|
} // extern "C"
|