Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#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"