Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2026-10-06 6bac54b555d27f1a85c1e4f011a6e7bd9111b0d0
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
#include "dbms_network_acl_utility.hpp"
 
extern "C"
{
#include "utils/builtins.h"
#include "utils/elog.h"
}
 
#include <map>
#include <list>
#include <algorithm>
#include <string>
#include <regex>
#include <vector>
#include <sstream>
#include <stdexcept>
#include <cstring>
#include <arpa/inet.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.*
        }
    }
    // Проверка: ':' - недопустимый символ
    if(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<std::string> host_octets;
    std::vector<std::string> 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<unsigned char>(c1)) ==
                   std::tolower(static_cast<unsigned char>(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<std::string> domains(const std::string& input) {
    std::list<std::string> 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<std::string> 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<std::string> 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<int>(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<std::string> 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<int>(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<std::string> 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<int>(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;
    }
}
 
int32 equals_host(const string &host1, const string &host2){
    // 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<string> 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"