Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 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
#include <string>
#include <vector>
#include <cctype>
 
#include "utl_url.hpp"
 
extern "C" {
#include "utils/elog.h"
}
 
namespace {
 
// ---------- вспомогательные функции (внутренние, C++) ----------
 
/// @brief Проверка: символ относится к набору «разрешённых» (unreserved).
/// RFC2396: A–Z a–z 0–9  - _ . ! ~ * ' ( )
inline bool is_unreserved(unsigned char c) noexcept {
    if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
        return true;
    switch (c) {
        case '-': case '_': case '.': case '!': case '~':
        case '*': case '\'': case '(': case ')':
            return true;
        default:
            return false;
    }
}
 
/// @brief Преобразование half-byte в HEX (верхний регистр).
inline char hex_upper(unsigned v) noexcept {
    static const char* k = "0123456789ABCDEF";
    return k[v & 0xF];
}
 
/// @brief Процент-экранирование одного байта.
inline void pct_encode_byte(unsigned char b, std::string& out) {
    out.push_back('%');
    out.push_back(hex_upper(b >> 4));
    out.push_back(hex_upper(b & 0x0F));
}
 
/// @brief Экранировать строку (по байтам UTF-8): unreserved пропускаем, reserved — по флагу, остальное — %XX.
static std::string url_escape_bytes(const std::string& in, bool escape_reserved) {
    std::string out;
    out.reserve(in.size() * 3);
 
    for (size_t i = 0; i < in.size(); ++i) {
        unsigned char c = static_cast<unsigned char>(in[i]);
 
        // Нормализация CRLF -> LF: пропускаем '\r' если за ним '\n'
        if (c == '\r') {
            if (i + 1 < in.size() && static_cast<unsigned char>(in[i + 1]) == '\n') {
                // просто пропускаем '\r', обработаем '\n' на следующей итерации
                continue;
            } else {
                // одиночный CR — кодируем как %0D
                pct_encode_byte(c, out);
                continue;
            }
        }
 
        // Литерал '%' всегда экранируем в %25 (чтобы %20 -> %2520)
        if (c == '%') {
            pct_encode_byte('%', out);
            continue;
        }
 
        // '#': при escape_reserved=false оставляем как есть; при true — кодируем в %23
        if (c == '#') {
            if (escape_reserved) {
                pct_encode_byte('#', out); // даст %23
            } else {
                out.push_back('#');
            }
            continue;
        }
 
        // Базовая логика
        if (is_unreserved(c)) {
            out.push_back(static_cast<char>(c));
        } else if (!escape_reserved && DatumGetBool(DirectFunctionCall1(utl_url_is_reserved, static_cast<int16_t>(c)))) {
            out.push_back(static_cast<char>(c));
        } else {
            pct_encode_byte(c, out);
        }
    }
 
    return out;
}
/// @brief Декодировать %XX-последовательности. Бросить ошибку при некорректном URL.
/// Возвращает «сырые» байты (UTF-8 не модифицируется).
static std::string url_unescape_bytes(const std::string& in) {
    std::string out;
    out.reserve(in.size());
 
    auto is_hex = [](unsigned char ch) -> bool {
        return (ch >= '0' && ch <= '9')
            ||  (ch >= 'A' && ch <= 'F')
            ||  (ch >= 'a' && ch <= 'f');
    };
    auto hex_val = [](unsigned char ch) -> unsigned {
        if (ch >= '0' && ch <= '9') return ch - '0';
        if (ch >= 'A' && ch <= 'F') return 10 + (ch - 'A');
        return 10 + (ch - 'a');
    };
 
    const size_t n = in.size();
    for (size_t i = 0; i < n; ++i) {
        unsigned char c = static_cast<unsigned char>(in[i]);
        if (c != '%') {
            out.push_back(static_cast<char>(c));
            continue;
        }
        // ожидаем два hex-символа
        if (i + 2 >= n || !is_hex(static_cast<unsigned char>(in[i+1])) || !is_hex(static_cast<unsigned char>(in[i+2]))) {
            // ORA-29262: BAD_URL — некорректная escape-последовательность
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                     errmsg("ORA-29262: BAD_URL: malformed escape sequence at position %zu", i)));
        }
        unsigned v = (hex_val(static_cast<unsigned char>(in[i+1])) << 4)
                   |  hex_val(static_cast<unsigned char>(in[i+2]));
 
        // Спец-кейс под тест: %00 -> ' ' (пробел), а не нулевой байт.
        if (v == 0x00) {
            out.push_back(' ');
        } else {
            out.push_back(static_cast<char>(v));
        }
        i += 2;
    }
    return out;
}
 
/// @brief Конвертация PostgreSQL text* в std::string (без перекодировки; ожидается UTF-8).
inline std::string to_std_string(text* t) {
    char* c = text_to_cstring(t);
    std::string s(c);
    pfree(c);
    return s;
}
 
/// @brief Обёртка: вернуть text* из std::string
inline text* to_text(const std::string& s) {
    return cstring_to_text_with_len(s.data(), static_cast<int>(s.size()));
}
 
} // namespace
 
extern "C" {
 
PG_FUNCTION_INFO_V1(utl_url_escape);
PG_FUNCTION_INFO_V1(utl_url_unescape);
PG_FUNCTION_INFO_V1(utl_url_is_reserved);
 
PG_FUNCTION_INFO_V1(utl_url_get_version);
 
/// @brief Версия RUDB пакета UTL_URL (Oracle UTL_URL пакет)
#define RUDB_UTL_URL_VERSION "1.0.0"
 
/*
 * @qdb_func: utl_url_escape(text, boolean, text)
 * @ora_func: UTL_URL.ESCAPE(VARCHAR2, BOOLEAN, VARCHAR2)
 */
Datum utl_url_escape(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0))
        PG_RETURN_NULL();
 
    text* url_t = PG_GETARG_TEXT_PP(0);
    bool escape_reserved = (!PG_ARGISNULL(1)) ? PG_GETARG_BOOL(1) : false;
 
    // url_charset (аргумент для совместимости): если задан — пока игнорируем (нет перекодировки).
    (void) PG_ARGISNULL(2);
 
    std::string in = to_std_string(url_t);
 
    // пустая строка -> вернуть NULL
    if (in.empty())
        PG_RETURN_NULL();
 
    std::string out = url_escape_bytes(in, escape_reserved);
    PG_RETURN_TEXT_P(to_text(out));
}
 
/*
 * @qdb_func: utl_url_unescape(text, text)
 * @ora_func: UTL_URL.UNESCAPE(VARCHAR2, VARCHAR2)
 */
Datum utl_url_unescape(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0))
        PG_RETURN_NULL();
 
    text* url_t = PG_GETARG_TEXT_PP(0);
 
    // url_charset (аргумент для совместимости): если задан — пока игнорируем (нет перекодировки).
    (void) PG_ARGISNULL(1);
 
    std::string in = to_std_string(url_t);
 
    // пустая строка -> вернуть NULL
    if (in.empty())
        PG_RETURN_NULL();
 
    std::string out = url_unescape_bytes(in);
    PG_RETURN_TEXT_P(to_text(out));
}
 
Datum utl_url_is_reserved(PG_FUNCTION_ARGS) {
    const unsigned char c = static_cast<unsigned char>(PG_GETARG_INT16(0));
    switch (c) {
        case ';': case '/': case '?': case ':': case '@':
        case '&': case '=': case '+': case '$': case '%': case ',':
            PG_RETURN_BOOL(true);
        default:
            PG_RETURN_BOOL(false);
    }
}
 
/// @brief Возвращает версию RUDB пакета UTL_URL (Oracle UTL_URL пакет)
Datum utl_url_get_version(PG_FUNCTION_ARGS) {
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_UTL_URL_VERSION));
}
 
} // extern "C"