extern "C" { #include "postgres.h" #include "fmgr.h" #include "utils/builtins.h" #include "funcapi.h" #include "access/htup_details.h" } #include #include #include #include #include #include #include #include #include #include "utl_http.hpp" // -------------------------- // Глобальные "сессионные" настройки (на backend процесс) // -------------------------- static int32 g_follow_redirects = 3; static int32 g_transfer_timeout = 60; // сек static bool g_resp_error_check = false; static std::string g_body_charset = "ISO-8859-1"; static std::string g_proxy; static std::string g_no_proxy_domains; // -------------------------- // Примитивные структуры состояния текущего запроса/ответа // (для упрощения — по одному активному REQ/RESP на backend) // -------------------------- struct Header { std::string name; std::string value; }; struct Cookie { std::string name; std::string value; std::string domain; std::string path; bool secure = false; int version = 0; std::string comment; // expire оставим пустым (NULL), конвертация time_t -> timestamptz опущена bool has_expire = false; long long expire_epoch = 0; }; struct Request { std::string url; std::string method = "GET"; std::string http_version; // не используем, но храним std::string https_host; // SNI hint (не используем явно) std::vector
headers; std::vector body; // auth std::string auth_user; std::string auth_pass; std::string auth_scheme; // "Basic" | "Digest" bool auth_for_proxy = false; }; struct Response { long status_code = 0; std::string reason_phrase; // libcurl не дает отдельную reason, оставим пустой std::string http_version; // из статусной строки std::vector
headers; std::string body; size_t read_pos = 0; // для READ_TEXT/READ_LINE/READ_RAW }; // Синглтон состояния static std::unique_ptr g_req; static std::unique_ptr g_resp; static std::vector g_cookiejar; // libcurl хэндл (reuse для keep-alive) static CURL* g_curl = nullptr; static bool g_curl_inited = false; static std::mutex g_curl_mtx; // -------------------------- // Вспомогалки // -------------------------- static inline std::string ltrim(std::string s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char c){return !std::isspace(c);} )); return s; } static inline std::string rtrim(std::string s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char c){return !std::isspace(c);} ).base(), s.end()); return s; } static inline std::string trim(std::string s) { return rtrim(ltrim(s)); } static size_t curl_write_cb(char* ptr, size_t size, size_t nmemb, void* userdata) { auto* body = reinterpret_cast(userdata); size_t real = size * nmemb; body->append(ptr, real); return real; } static size_t curl_header_cb(char* ptr, size_t size, size_t nmemb, void* userdata) { auto* resp = reinterpret_cast(userdata); size_t real = size * nmemb; // Строки заголовков оканчиваются \r\n, статусная строка тоже приходит здесь. std::string line(ptr, real); // Отсекать \r\n while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) line.pop_back(); if (line.empty()) return real; // Статусная строка: "HTTP/1.1 200 OK" if (line.rfind("HTTP/", 0) == 0) { resp->http_version = line.substr(0, line.find(' ')); return real; } // Обычный заголовок: "Name: value" auto pos = line.find(':'); if (pos != std::string::npos) { Header h; h.name = line.substr(0, pos); h.value = trim(line.substr(pos + 1)); resp->headers.push_back(std::move(h)); } return real; } static void ensure_curl() { std::lock_guard lk(g_curl_mtx); if (!g_curl_inited) { curl_global_init(CURL_GLOBAL_DEFAULT); g_curl_inited = true; } if (!g_curl) { g_curl = curl_easy_init(); // включим cookie-движок в памяти if (g_curl) curl_easy_setopt(g_curl, CURLOPT_COOKIEFILE, ""); } } static int do_http_perform(Request& req, Response& out, std::vector& out_cookies, std::string& err) { ensure_curl(); if (!g_curl) { err = "curl init failed"; return -1; } out = Response{}; out_cookies.clear(); curl_easy_reset(g_curl); curl_easy_setopt(g_curl, CURLOPT_URL, req.url.c_str()); curl_easy_setopt(g_curl, CURLOPT_USERAGENT, "QDB-UTL_HTTP/1.0"); curl_easy_setopt(g_curl, CURLOPT_WRITEFUNCTION, curl_write_cb); curl_easy_setopt(g_curl, CURLOPT_WRITEDATA, &out.body); curl_easy_setopt(g_curl, CURLOPT_HEADERFUNCTION, curl_header_cb); curl_easy_setopt(g_curl, CURLOPT_HEADERDATA, &out); // proxy if (!g_proxy.empty()) { curl_easy_setopt(g_curl, CURLOPT_PROXY, g_proxy.c_str()); } else { curl_easy_setopt(g_curl, CURLOPT_PROXY, nullptr); } if (!g_no_proxy_domains.empty()) { curl_easy_setopt(g_curl, CURLOPT_NOPROXY, g_no_proxy_domains.c_str()); } // таймауты long to = (g_transfer_timeout > 0) ? g_transfer_timeout : 0; if (to > 0) { curl_easy_setopt(g_curl, CURLOPT_TIMEOUT, to); curl_easy_setopt(g_curl, CURLOPT_CONNECTTIMEOUT, to); } // редиректы curl_easy_setopt(g_curl, CURLOPT_FOLLOWLOCATION, g_follow_redirects > 0 ? 1L : 0L); curl_easy_setopt(g_curl, CURLOPT_MAXREDIRS, (long) std::max(0, g_follow_redirects)); // метод / тело struct curl_slist* hdrs = nullptr; for (auto& h : req.headers) { std::string line = h.name + ": " + h.value; hdrs = curl_slist_append(hdrs, line.c_str()); } if (hdrs) curl_easy_setopt(g_curl, CURLOPT_HTTPHEADER, hdrs); // auth if (!req.auth_user.empty()) { curl_easy_setopt(g_curl, CURLOPT_USERNAME, req.auth_user.c_str()); curl_easy_setopt(g_curl, CURLOPT_PASSWORD, req.auth_pass.c_str()); if (!req.auth_scheme.empty() && strcasecmp(req.auth_scheme.c_str(), "digest") == 0) { curl_easy_setopt(g_curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST); } else { curl_easy_setopt(g_curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC); } } // метод std::string m = req.method; std::transform(m.begin(), m.end(), m.begin(), [](unsigned char c){return std::toupper(c);}); if (m == "GET") { curl_easy_setopt(g_curl, CURLOPT_HTTPGET, 1L); if (!req.body.empty()) { // если пользователь всё-таки пишет тело — сделаем POST curl_easy_setopt(g_curl, CURLOPT_POST, 1L); curl_easy_setopt(g_curl, CURLOPT_POSTFIELDS, (const char*)req.body.data()); curl_easy_setopt(g_curl, CURLOPT_POSTFIELDSIZE, (long)req.body.size()); } } else if (m == "POST") { curl_easy_setopt(g_curl, CURLOPT_POST, 1L); if (!req.body.empty()) { curl_easy_setopt(g_curl, CURLOPT_POSTFIELDS, (const char*)req.body.data()); curl_easy_setopt(g_curl, CURLOPT_POSTFIELDSIZE, (long)req.body.size()); } else { curl_easy_setopt(g_curl, CURLOPT_POSTFIELDS, ""); curl_easy_setopt(g_curl, CURLOPT_POSTFIELDSIZE, 0L); } } else { // произвольный метод curl_easy_setopt(g_curl, CURLOPT_CUSTOMREQUEST, req.method.c_str()); if (!req.body.empty()) { curl_easy_setopt(g_curl, CURLOPT_POSTFIELDS, (const char*)req.body.data()); curl_easy_setopt(g_curl, CURLOPT_POSTFIELDSIZE, (long)req.body.size()); } } CURLcode rc = curl_easy_perform(g_curl); long http_code = 0; curl_easy_getinfo(g_curl, CURLINFO_RESPONSE_CODE, &http_code); out.status_code = http_code; if (hdrs) { curl_slist_free_all(hdrs); hdrs = nullptr; } if (rc != CURLE_OK) { err = curl_easy_strerror(rc); return -2; } // cookies (из cookie-энджина libcurl) struct curl_slist* cookie_list = nullptr; if (curl_easy_getinfo(g_curl, CURLINFO_COOKIELIST, &cookie_list) == CURLE_OK && cookie_list) { for (auto* it = cookie_list; it; it = it->next) { // формат: Netscape cookie file format, табы; колонки: domain flag path secure expiration name value std::string line = it->data ? it->data : ""; Cookie c; // распарсим осторожно std::vector cols; size_t start = 0; while (true) { size_t tab = line.find('\t', start); if (tab == std::string::npos) { cols.push_back(line.substr(start)); break; } cols.push_back(line.substr(start, tab - start)); start = tab + 1; } if (cols.size() >= 7) { c.domain = cols[0]; // cols[1] флаг c.path = cols[2]; c.secure = (cols[3] == "TRUE"); // cols[4] expire (epoch) try { c.expire_epoch = std::stoll(cols[4]); c.has_expire = (c.expire_epoch > 0); } catch (...) { c.has_expire = false; } c.name = cols[5]; c.value = cols[6]; } out_cookies.push_back(std::move(c)); } curl_slist_free_all(cookie_list); } return 0; } extern "C" { PG_FUNCTION_INFO_V1(utl_http_request); PG_FUNCTION_INFO_V1(utl_http_request_extended); PG_FUNCTION_INFO_V1(utl_http_request_pieces); PG_FUNCTION_INFO_V1(utl_http_begin_request); PG_FUNCTION_INFO_V1(utl_http_set_header); PG_FUNCTION_INFO_V1(utl_http_set_authentication); PG_FUNCTION_INFO_V1(utl_http_set_authentication_from_wallet); PG_FUNCTION_INFO_V1(utl_http_set_body_charset_req); PG_FUNCTION_INFO_V1(utl_http_set_cookie_support_req); PG_FUNCTION_INFO_V1(utl_http_set_follow_redirect_req); PG_FUNCTION_INFO_V1(utl_http_set_persistent_conn_support_req); PG_FUNCTION_INFO_V1(utl_http_write_line); PG_FUNCTION_INFO_V1(utl_http_write_text); PG_FUNCTION_INFO_V1(utl_http_write_raw); PG_FUNCTION_INFO_V1(utl_http_end_request); PG_FUNCTION_INFO_V1(utl_http_get_response); PG_FUNCTION_INFO_V1(utl_http_end_response); PG_FUNCTION_INFO_V1(utl_http_get_authentication); PG_FUNCTION_INFO_V1(utl_http_get_header); PG_FUNCTION_INFO_V1(utl_http_get_header_by_name); PG_FUNCTION_INFO_V1(utl_http_get_header_count); PG_FUNCTION_INFO_V1(utl_http_read_line); PG_FUNCTION_INFO_V1(utl_http_read_text); PG_FUNCTION_INFO_V1(utl_http_read_raw); PG_FUNCTION_INFO_V1(utl_http_set_body_charset_resp); PG_FUNCTION_INFO_V1(utl_http_add_cookies); PG_FUNCTION_INFO_V1(utl_http_clear_cookies); PG_FUNCTION_INFO_V1(utl_http_get_cookie_count); PG_FUNCTION_INFO_V1(utl_http_get_cookies); PG_FUNCTION_INFO_V1(utl_http_get_body_charset); PG_FUNCTION_INFO_V1(utl_http_set_body_charset_session); PG_FUNCTION_INFO_V1(utl_http_get_cookie_support); PG_FUNCTION_INFO_V1(utl_http_set_cookie_support_session); PG_FUNCTION_INFO_V1(utl_http_get_follow_redirect); PG_FUNCTION_INFO_V1(utl_http_set_follow_redirect_session); PG_FUNCTION_INFO_V1(utl_http_get_persistent_conn_support); PG_FUNCTION_INFO_V1(utl_http_set_persistent_conn_support_session); PG_FUNCTION_INFO_V1(utl_http_get_proxy); PG_FUNCTION_INFO_V1(utl_http_set_proxy); PG_FUNCTION_INFO_V1(utl_http_get_response_error_check); PG_FUNCTION_INFO_V1(utl_http_set_response_error_check); PG_FUNCTION_INFO_V1(utl_http_get_transfer_timeout); PG_FUNCTION_INFO_V1(utl_http_set_transfer_timeout); PG_FUNCTION_INFO_V1(utl_http_set_wallet); PG_FUNCTION_INFO_V1(utl_http_get_detailed_excp_support); PG_FUNCTION_INFO_V1(utl_http_set_detailed_excp_support); PG_FUNCTION_INFO_V1(utl_http_get_persistent_conn_count); PG_FUNCTION_INFO_V1(utl_http_get_persistent_conns); PG_FUNCTION_INFO_V1(utl_http_close_persistent_conn); PG_FUNCTION_INFO_V1(utl_http_close_persistent_conns); PG_FUNCTION_INFO_V1(utl_http_create_request_context); PG_FUNCTION_INFO_V1(utl_http_destroy_request_context); PG_FUNCTION_INFO_V1(utl_http_get_detailed_sqlcode); PG_FUNCTION_INFO_V1(utl_http_get_detailed_sqlerrm); PG_FUNCTION_INFO_V1(utl_http_get_response_error_check_fn); PG_FUNCTION_INFO_V1(utl_http_get_detailed_excp_support_fn); PG_FUNCTION_INFO_V1(utl_http_get_version); /// @brief Версия RUDB пакета UTL_HTTP (Oracle UTL_HTTP пакет) #define RUDB_UTL_HTTP_VERSION "1.0.0" } // extern "C" extern "C" { // ---------- SIMPLE FETCH ---------- Datum utl_http_request(PG_FUNCTION_ARGS) { LOCAL_FCINFO(fcinfo2, 6); InitFunctionCallInfoData(*fcinfo2, fcinfo->flinfo, 6, PG_GET_COLLATION(), fcinfo->context, NULL); for (int i = 0; i < 5; ++i) { fcinfo2->args[i].value = (PG_NARGS() > i) ? fcinfo->args[i].value : (Datum) 0; fcinfo2->args[i].isnull = (PG_NARGS() > i) ? fcinfo->args[i].isnull : true; } fcinfo2->args[5].value = Int32GetDatum(0); fcinfo2->args[5].isnull = false; return utl_http_request_extended(fcinfo2); } Datum utl_http_request_extended(PG_FUNCTION_ARGS) { const char* url = PG_NARGS() >= 1 && !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : ""; const char* proxy = PG_NARGS() >= 2 && !PG_ARGISNULL(1) ? text_to_cstring(PG_GETARG_TEXT_PP(1)) : ""; const char* wallet_path = PG_NARGS() >= 3 && !PG_ARGISNULL(2) ? text_to_cstring(PG_GETARG_TEXT_PP(2)) : ""; const char* wallet_password = PG_NARGS() >= 4 && !PG_ARGISNULL(3) ? text_to_cstring(PG_GETARG_TEXT_PP(3)) : ""; const char* https_host = PG_NARGS() >= 5 && !PG_ARGISNULL(4) ? text_to_cstring(PG_GETARG_TEXT_PP(4)) : ""; int32 options = PG_NARGS() >= 6 && !PG_ARGISNULL(5) ? PG_GETARG_INT32(5) : 0; const int32 minimum_options = -128; const int32 supported_option_mask = 0x03; bool compatibility_mode = (options & 0x01) != 0; bool preserve_request_hints = (options & 0x02) != 0; if (options < minimum_options) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_HTTP.REQUEST: invalid options"))); options &= supported_option_mask; Request req; req.url = url; req.method = "GET"; if (compatibility_mode && proxy != nullptr && *proxy != '\0') req.https_host.reserve(strlen(proxy)); if (preserve_request_hints && https_host != nullptr && *https_host != '\0') req.https_host = https_host; if (wallet_path != nullptr && *wallet_path != '\0') req.http_version.reserve(strlen(wallet_path)); if (wallet_password != nullptr && *wallet_password != '\0') req.method.reserve(req.method.size()); Response resp; std::vector cookies; std::string err; int r = do_http_perform(req, resp, cookies, err); if (r != 0) { if (g_resp_error_check) ereport(ERROR, (errmsg("UTL_HTTP.REQUEST failed: %s", err.c_str()))); std::string emsg = "

HTTP error

";
        emsg += err;
        emsg += "
"; PG_RETURN_TEXT_P(cstring_to_text(emsg.c_str())); } g_cookiejar = cookies; std::string s = resp.body.substr(0, 2000); (void) options; PG_RETURN_TEXT_P(cstring_to_text_with_len(s.c_str(), s.size())); } Datum utl_http_request_pieces(PG_FUNCTION_ARGS) { FuncCallContext* funcctx; typedef struct { std::vector pieces; size_t idx; } Ctx; if (SRF_IS_FIRSTCALL()) { funcctx = SRF_FIRSTCALL_INIT(); MemoryContext oldctx = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); const char* url = (PG_NARGS() >= 1 && !PG_ARGISNULL(0)) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : ""; int32 max_pieces = (PG_NARGS() >= 2 && !PG_ARGISNULL(1)) ? PG_GETARG_INT32(1) : 32767; Request req; req.url = url; req.method = "GET"; Response resp; std::vector cookies; std::string err; int r = do_http_perform(req, resp, cookies, err); if (r != 0) { // вернем один кусок с текстом ошибки auto* ctx = (Ctx*) palloc0(sizeof(Ctx)); ctx->idx = 0; std::string emsg = std::string("HTTP error: ") + err; ctx->pieces.push_back(emsg); funcctx->user_fctx = ctx; MemoryContextSwitchTo(oldctx); } else { g_cookiejar = cookies; auto* ctx = (Ctx*) palloc0(sizeof(Ctx)); ctx->idx = 0; // разрежем по 2000 символов const std::string& b = resp.body; size_t pos = 0; while (pos < b.size() && (int)ctx->pieces.size() < max_pieces) { size_t chunk = std::min(2000, b.size() - pos); ctx->pieces.emplace_back(b.substr(pos, chunk)); pos += chunk; } funcctx->user_fctx = ctx; MemoryContextSwitchTo(oldctx); } } funcctx = SRF_PERCALL_SETUP(); auto* ctx = (Ctx*) funcctx->user_fctx; if (ctx->idx < ctx->pieces.size()) { text* t = cstring_to_text(ctx->pieces[ctx->idx].c_str()); ctx->idx++; SRF_RETURN_NEXT(funcctx, PointerGetDatum(t)); } SRF_RETURN_DONE(funcctx); } // ---------- REQUEST API ---------- /* * @qdb_func: utl_http_begin_request(text, text, text, int4, text) * @ora_func: UTL_HTTP.BEGIN_REQUEST(VARCHAR2, VARCHAR2, VARCHAR2, BINARY_INTEGER, VARCHAR2) */ Datum utl_http_begin_request(PG_FUNCTION_ARGS) { const char* url = (PG_NARGS() >= 1 && !PG_ARGISNULL(0)) ? text_to_cstring(PG_GETARG_TEXT_PP(0)) : ""; const char* method = (PG_NARGS() >= 2 && !PG_ARGISNULL(1)) ? text_to_cstring(PG_GETARG_TEXT_PP(1)) : "GET"; const char* http_ver = (PG_NARGS() >= 3 && !PG_ARGISNULL(2)) ? text_to_cstring(PG_GETARG_TEXT_PP(2)) : ""; // request_context (int4) игнорируем — у нас один контекст в процессе const char* https_host = (PG_NARGS() >= 5 && !PG_ARGISNULL(4)) ? text_to_cstring(PG_GETARG_TEXT_PP(4)) : ""; g_req = std::make_unique(); g_req->url = url ? url : ""; g_req->method = method ? method : "GET"; g_req->http_version = http_ver ? http_ver : ""; g_req->https_host = https_host ? https_host : ""; g_resp.reset(); // сбросить предыдущий ответ // Возвращаем «идентификатор запроса» (просто 1) PG_RETURN_INT32(1); } /* * @qdb_func: utl_http_set_header(int4, text, text) * @ora_func: UTL_HTTP.SET_HEADER(R PL/SQL_RECORD, VARCHAR2, VARCHAR2) */ Datum utl_http_set_header(PG_FUNCTION_ARGS) { if (!g_req) PG_RETURN_NULL(); const char* name = (PG_NARGS() >= 2 && !PG_ARGISNULL(1)) ? text_to_cstring(PG_GETARG_TEXT_PP(1)) : ""; const char* value = (PG_NARGS() >= 3 && !PG_ARGISNULL(2)) ? text_to_cstring(PG_GETARG_TEXT_PP(2)) : ""; if (name && *name) { Header h; h.name = name; h.value = value ? value : ""; g_req->headers.push_back(std::move(h)); } PG_RETURN_NULL(); } /* * @qdb_func: utl_http_set_authentication(int4, text, text, text, boolean) * @ora_func: UTL_HTTP.SET_AUTHENTICATION(R PL/SQL_RECORD, VARCHAR2, VARCHAR2, VARCHAR2, BOOLEAN) */ Datum utl_http_set_authentication(PG_FUNCTION_ARGS) { if (!g_req) PG_RETURN_NULL(); const char* username = (PG_NARGS() >= 2 && !PG_ARGISNULL(1)) ? text_to_cstring(PG_GETARG_TEXT_PP(1)) : ""; const char* password = (PG_NARGS() >= 3 && !PG_ARGISNULL(2)) ? text_to_cstring(PG_GETARG_TEXT_PP(2)) : ""; const char* scheme = (PG_NARGS() >= 4 && !PG_ARGISNULL(3)) ? text_to_cstring(PG_GETARG_TEXT_PP(3)) : "Basic"; bool for_proxy = (PG_NARGS() >= 5 && !PG_ARGISNULL(4)) ? PG_GETARG_BOOL(4) : false; g_req->auth_user = username ? username : ""; g_req->auth_pass = password ? password : ""; g_req->auth_scheme = scheme ? scheme : "Basic"; g_req->auth_for_proxy = for_proxy; PG_RETURN_NULL(); } /* * @qdb_func: utl_http_set_authentication_from_wallet(int4, text, text, boolean) * @ora_func: UTL_HTTP.SET_AUTHENTICATION_FROM_WALLET(R PL/SQL_RECORD, VARCHAR2, VARCHAR2, BOOLEAN) */ Datum utl_http_set_authentication_from_wallet(PG_FUNCTION_ARGS) { // Нет кошелька — заглушка PG_RETURN_NULL(); } Datum utl_http_set_body_charset_req(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } Datum utl_http_set_cookie_support_req(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } Datum utl_http_set_follow_redirect_req(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } Datum utl_http_set_persistent_conn_support_req(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } /* * @qdb_func: utl_http_write_line(int4, text) * @ora_func: UTL_HTTP.WRITE_LINE(R PL/SQL_RECORD, VARCHAR2) */ Datum utl_http_write_line(PG_FUNCTION_ARGS) { if (!g_req) PG_RETURN_NULL(); if (PG_NARGS() >= 2 && !PG_ARGISNULL(1)) { text* t = PG_GETARG_TEXT_PP(1); size_t len = VARSIZE_ANY_EXHDR(t); g_req->body.insert(g_req->body.end(), VARDATA_ANY(t), VARDATA_ANY(t) + len); // CRLF g_req->body.push_back('\r'); g_req->body.push_back('\n'); } PG_RETURN_NULL(); } /* * @qdb_func: utl_http_write_text(int4, text) * @ora_func: UTL_HTTP.WRITE_TEXT(R PL/SQL_RECORD, VARCHAR2) */ Datum utl_http_write_text(PG_FUNCTION_ARGS) { if (!g_req) PG_RETURN_NULL(); if (PG_NARGS() >= 2 && !PG_ARGISNULL(1)) { text* t = PG_GETARG_TEXT_PP(1); size_t len = VARSIZE_ANY_EXHDR(t); g_req->body.insert(g_req->body.end(), VARDATA_ANY(t), VARDATA_ANY(t) + len); } PG_RETURN_NULL(); } /* * @qdb_func: utl_http_write_raw(int4, raw) * @ora_func: UTL_HTTP.WRITE_RAW(R PL/SQL_RECORD, RAW) */ Datum utl_http_write_raw(PG_FUNCTION_ARGS) { if (!g_req) PG_RETURN_NULL(); if (PG_NARGS() >= 2 && !PG_ARGISNULL(1)) { bytea* b = PG_GETARG_BYTEA_P(1); size_t len = VARSIZE_ANY_EXHDR(b); g_req->body.insert(g_req->body.end(), (unsigned char*)VARDATA_ANY(b), (unsigned char*)VARDATA_ANY(b) + len); } PG_RETURN_NULL(); } /* * @qdb_func: utl_http_end_request(int4) * @ora_func: UTL_HTTP.END_REQUEST(R PL/SQL_RECORD) */ Datum utl_http_end_request(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } // ---------- RESPONSE API ---------- /* * @qdb_func: utl_http_get_response(int4, boolean) * @ora_func: UTL_HTTP.GET_RESPONSE(R PL/SQL_RECORD, BOOLEAN) */ Datum utl_http_get_response(PG_FUNCTION_ARGS) { if (!g_req) PG_RETURN_INT32(0); Response resp; std::vector cookies; std::string err; int r = do_http_perform(*g_req, resp, cookies, err); if (r != 0) { if (g_resp_error_check) ereport(ERROR, (errmsg("UTL_HTTP.GET_RESPONSE failed: %s", err.c_str()))); // иначе просто оставим статус 0, тело = сообщение } g_resp = std::make_unique(std::move(resp)); g_cookiejar = std::move(cookies); // Возвращаем «идентификатор ответа» (просто 1) PG_RETURN_INT32(1); } /* * @qdb_func: utl_http_end_response(int4) * @ora_func: UTL_HTTP.END_RESPONSE(R PL/SQL_RECORD) */ Datum utl_http_end_response(PG_FUNCTION_ARGS) { g_resp.reset(); PG_RETURN_NULL(); } Datum utl_http_get_authentication(PG_FUNCTION_ARGS) { // Для простоты: не извлекаем realm/challenge — заглушка // Возвращайте пустые значения через OUT (или игнорируйте в SQL). PG_RETURN_NULL(); } /* * @qdb_func: utl_http_get_header(int4, int4) * @ora_func: UTL_HTTP.GET_HEADER(R PL/SQL_RECORD, BINARY_INTEGER, VARCHAR2, VARCHAR2) */ Datum utl_http_get_header(PG_FUNCTION_ARGS) { if (!g_resp) PG_RETURN_NULL(); // ожидаем: (resp_id, n OUT name, OUT value) — мы игнорируем resp_id и возвращаем record TupleDesc tupdesc; Datum values[2]; bool nulls[2] = {true, true}; if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) ereport(ERROR, (errmsg("utl_http_get_header must be called in context expecting a record"))); int32 n = (PG_NARGS() >= 2 && !PG_ARGISNULL(1)) ? PG_GETARG_INT32(1) : 1; if (n >= 1 && (size_t)n <= g_resp->headers.size()) { auto& h = g_resp->headers[n-1]; values[0] = CStringGetTextDatum(h.name.c_str()); nulls[0] = false; values[1] = CStringGetTextDatum(h.value.c_str()); nulls[1] = false; } HeapTuple tuple = heap_form_tuple(tupdesc, values, nulls); PG_RETURN_DATUM(HeapTupleGetDatum(tuple)); } Datum utl_http_get_header_by_name(PG_FUNCTION_ARGS) { if (!g_resp) PG_RETURN_NULL(); const char* name = (PG_NARGS() >= 2 && !PG_ARGISNULL(1)) ? text_to_cstring(PG_GETARG_TEXT_PP(1)) : ""; int32 nth = (PG_NARGS() >= 3 && !PG_ARGISNULL(2)) ? PG_GETARG_INT32(2) : 1; if (!name || !*name) PG_RETURN_NULL(); int seen = 0; for (auto& h : g_resp->headers) { if (strcasecmp(h.name.c_str(), name) == 0) { seen++; if (seen == nth) { PG_RETURN_TEXT_P(cstring_to_text(h.value.c_str())); } } } PG_RETURN_NULL(); } /* * @qdb_func: utl_http_get_header_count(int4) * @ora_func: UTL_HTTP.GET_HEADER_COUNT(R PL/SQL_RECORD) */ Datum utl_http_get_header_count(PG_FUNCTION_ARGS) { if (!g_resp) PG_RETURN_INT32(0); PG_RETURN_INT32((int32) g_resp->headers.size()); } Datum utl_http_read_line(PG_FUNCTION_ARGS) { if (!g_resp) PG_RETURN_NULL(); auto& b = g_resp->body; size_t pos = g_resp->read_pos; if (pos >= b.size()) PG_RETURN_NULL(); size_t nl = b.find('\n', pos); std::string line; if (nl == std::string::npos) { line = b.substr(pos); g_resp->read_pos = b.size(); } else { line = b.substr(pos, nl - pos); // срежем завершающий \r при наличии if (!line.empty() && line.back() == '\r') line.pop_back(); g_resp->read_pos = nl + 1; } PG_RETURN_TEXT_P(cstring_to_text(line.c_str())); } /* * @qdb_func: utl_http_read_text(int4, int4) * @ora_func: UTL_HTTP.READ_TEXT(R PL/SQL_RECORD, VARCHAR2, BINARY_INTEGER) */ Datum utl_http_read_text(PG_FUNCTION_ARGS) { if (!g_resp) PG_RETURN_NULL(); auto& b = g_resp->body; size_t pos = g_resp->read_pos; if (pos >= b.size()) PG_RETURN_NULL(); // Oracle позволяет указывать len — у нас нет параметра в SQL-обертке, отдадим всё оставшееся std::string chunk = b.substr(pos); g_resp->read_pos = b.size(); PG_RETURN_TEXT_P(cstring_to_text_with_len(chunk.c_str(), chunk.size())); } /* * @qdb_func: utl_http_read_raw(int4, int4) * @ora_func: UTL_HTTP.READ_RAW(R PL/SQL_RECORD, RAW, BINARY_INTEGER) */ Datum utl_http_read_raw(PG_FUNCTION_ARGS) { if (!g_resp) PG_RETURN_NULL(); auto& b = g_resp->body; size_t pos = g_resp->read_pos; if (pos >= b.size()) PG_RETURN_NULL(); std::string chunk = b.substr(pos); g_resp->read_pos = b.size(); bytea* out = (bytea*)palloc(chunk.size() + VARHDRSZ); SET_VARSIZE(out, chunk.size() + VARHDRSZ); memcpy(VARDATA(out), chunk.data(), chunk.size()); PG_RETURN_BYTEA_P(out); } Datum utl_http_set_body_charset_resp(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } // ---------- COOKIES ---------- Datum utl_http_add_cookies(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } /* * @qdb_func: utl_http_clear_cookies(int4) * @ora_func: UTL_HTTP.CLEAR_COOKIES(BINARY_INTEGER) */ Datum utl_http_clear_cookies(PG_FUNCTION_ARGS) { g_cookiejar.clear(); PG_RETURN_NULL(); } /* * @qdb_func: utl_http_get_cookie_count(int4) * @ora_func: UTL_HTTP.GET_COOKIE_COUNT(BINARY_INTEGER) */ Datum utl_http_get_cookie_count(PG_FUNCTION_ARGS) { PG_RETURN_INT32((int32) g_cookiejar.size()); } /* * @qdb_func: utl_http_get_cookies(int4) * @ora_func: UTL_HTTP.GET_COOKIES(COOKIES PL/SQL_TABLE, BINARY_INTEGER) */ Datum utl_http_get_cookies(PG_FUNCTION_ARGS) { FuncCallContext* funcctx; typedef struct { size_t idx; } Ctx; if (SRF_IS_FIRSTCALL()) { funcctx = SRF_FIRSTCALL_INIT(); MemoryContext oldctx = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); auto* ctx = (Ctx*) palloc0(sizeof(Ctx)); ctx->idx = 0; funcctx->user_fctx = ctx; MemoryContextSwitchTo(oldctx); } funcctx = SRF_PERCALL_SETUP(); auto* ctx = (Ctx*) funcctx->user_fctx; TupleDesc tupdesc; if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) ereport(ERROR, (errmsg("utl_http_get_cookies must be called in context expecting a record"))); if (ctx->idx < g_cookiejar.size()) { const Cookie& c = g_cookiejar[ctx->idx++]; Datum values[9]; bool nulls[9]; memset(nulls, 0, sizeof(nulls)); values[0] = CStringGetTextDatum(c.name.c_str()); values[1] = CStringGetTextDatum(c.value.c_str()); values[2] = CStringGetTextDatum(c.domain.c_str()); // Упростим: не конвертируем epoch -> timestamptz, вернём NULL (Oracle тоже допускает сессионные без expire) nulls[3] = true; values[4] = CStringGetTextDatum(c.path.c_str()); values[5] = BoolGetDatum(c.secure); values[6] = Int32GetDatum(c.version); values[7] = CStringGetTextDatum(c.comment.c_str()); // Внимание к порядку полей: OUT name,value,domain,expire,path,secure,version,comment // Мы заполнили values[0..7]; если в SQL 9 полей — сдвинуть при необходимост?*() HeapTuple tuple = heap_form_tuple(tupdesc, values, nulls); SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple)); } SRF_RETURN_DONE(funcctx); } // ---------- SESSION SETTINGS ---------- /* * @qdb_func: utl_http_get_body_charset() * @ora_func: UTL_HTTP.GET_BODY_CHARSET(VARCHAR2) * @ora_func: UTL_HTTP.GET_BODY_CHARSET() */ Datum utl_http_get_body_charset(PG_FUNCTION_ARGS) { text* t = cstring_to_text(g_body_charset.c_str()); PG_RETURN_TEXT_P(t); } Datum utl_http_set_body_charset_session(PG_FUNCTION_ARGS) { if (PG_NARGS() >= 1 && !PG_ARGISNULL(0)) { const char* cs = text_to_cstring(PG_GETARG_TEXT_PP(0)); g_body_charset = cs ? cs : ""; } PG_RETURN_NULL(); } /* * @qdb_func: utl_http_get_cookie_support() * @ora_func: UTL_HTTP.GET_COOKIE_SUPPORT(BOOLEAN, BINARY_INTEGER, BINARY_INTEGER) */ Datum utl_http_get_cookie_support(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } Datum utl_http_set_cookie_support_session(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } /* * @qdb_func: utl_http_get_follow_redirect() * @ora_func: UTL_HTTP.GET_FOLLOW_REDIRECT(BINARY_INTEGER) */ Datum utl_http_get_follow_redirect(PG_FUNCTION_ARGS) { PG_RETURN_INT32(g_follow_redirects); } Datum utl_http_set_follow_redirect_session(PG_FUNCTION_ARGS) { if (PG_NARGS() >= 1 && !PG_ARGISNULL(0)) { int32 v = PG_GETARG_INT32(0); if (v < 0) v = 0; g_follow_redirects = v; } PG_RETURN_NULL(); } /* * @qdb_func: utl_http_get_persistent_conn_support() * @ora_func: UTL_HTTP.GET_PERSISTENT_CONN_SUPPORT(BOOLEAN, BINARY_INTEGER) */ Datum utl_http_get_persistent_conn_support(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } Datum utl_http_set_persistent_conn_support_session(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } /* * @qdb_func: utl_http_get_proxy() * @ora_func: UTL_HTTP.GET_PROXY(VARCHAR2, VARCHAR2) */ Datum utl_http_get_proxy(PG_FUNCTION_ARGS) { TupleDesc tupdesc; Datum values[2]; bool nulls[2] = {false, false}; if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) ereport(ERROR, (errmsg("utl_http_get_proxy must be called in context expecting a record"))); values[0] = CStringGetTextDatum(g_proxy.c_str()); values[1] = CStringGetTextDatum(g_no_proxy_domains.c_str()); HeapTuple tuple = heap_form_tuple(tupdesc, values, nulls); PG_RETURN_DATUM(HeapTupleGetDatum(tuple)); } /* * @qdb_func: utl_http_set_proxy(text, text) * @ora_func: UTL_HTTP.SET_PROXY(VARCHAR2, VARCHAR2) */ Datum utl_http_set_proxy(PG_FUNCTION_ARGS) { if (PG_NARGS() >= 1) { if (!PG_ARGISNULL(0)) g_proxy = text_to_cstring(PG_GETARG_TEXT_PP(0)); else g_proxy.clear(); } if (PG_NARGS() >= 2) { if (!PG_ARGISNULL(1)) g_no_proxy_domains = text_to_cstring(PG_GETARG_TEXT_PP(1)); else g_no_proxy_domains.clear(); } PG_RETURN_NULL(); } /* * @qdb_func: utl_http_get_response_error_check() * @ora_func: UTL_HTTP.GET_RESPONSE_ERROR_CHECK(BOOLEAN) */ Datum utl_http_get_response_error_check(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(g_resp_error_check); } /* * @qdb_func: utl_http_set_response_error_check(boolean) * @ora_func: UTL_HTTP.SET_RESPONSE_ERROR_CHECK(BOOLEAN) * @ora_func: UTL_HTTP.SET_RESPONSE_ERROR_CHECK(R PL/SQL_RECORD, BOOLEAN) */ Datum utl_http_set_response_error_check(PG_FUNCTION_ARGS) { if (PG_NARGS() >= 1 && !PG_ARGISNULL(0)) g_resp_error_check = PG_GETARG_BOOL(0); PG_RETURN_NULL(); } /* * @qdb_func: utl_http_get_transfer_timeout() * @ora_func: UTL_HTTP.GET_TRANSFER_TIMEOUT(BINARY_INTEGER) */ Datum utl_http_get_transfer_timeout(PG_FUNCTION_ARGS) { PG_RETURN_INT32(g_transfer_timeout); } /* * @qdb_func: utl_http_set_transfer_timeout(int4) * @ora_func: UTL_HTTP.SET_TRANSFER_TIMEOUT(BINARY_INTEGER) * @ora_func: UTL_HTTP.SET_TRANSFER_TIMEOUT(R PL/SQL_RECORD, BINARY_INTEGER) */ Datum utl_http_set_transfer_timeout(PG_FUNCTION_ARGS) { if (PG_NARGS() >= 1 && !PG_ARGISNULL(0)) { int32 v = PG_GETARG_INT32(0); if (v < 0) v = 0; g_transfer_timeout = v; } PG_RETURN_NULL(); } /* * @qdb_func: utl_http_set_wallet(text, text) * @ora_func: UTL_HTTP.SET_WALLET(VARCHAR2, VARCHAR2) */ Datum utl_http_set_wallet(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } /* * @qdb_func: utl_http_get_detailed_excp_support() * @ora_func: UTL_HTTP.GET_DETAILED_EXCP_SUPPORT(BOOLEAN) */ Datum utl_http_get_detailed_excp_support(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(false); } /* * @qdb_func: utl_http_set_detailed_excp_support(boolean) * @ora_func: UTL_HTTP.SET_DETAILED_EXCP_SUPPORT(BOOLEAN) */ Datum utl_http_set_detailed_excp_support(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } // ---------- PERSISTENT CONNECTIONS ---------- /* * @qdb_func: utl_http_get_persistent_conn_count() * @ora_func: UTL_HTTP.GET_PERSISTENT_CONN_COUNT() */ Datum utl_http_get_persistent_conn_count(PG_FUNCTION_ARGS) { PG_RETURN_INT32( (g_curl ? 1 : 0) ); } /* * @qdb_func: utl_http_get_persistent_conns() * @ora_func: UTL_HTTP.GET_PERSISTENT_CONNS(CONNECTIONS PL/SQL_TABLE) */ Datum utl_http_get_persistent_conns(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } /* * @qdb_func: utl_http_close_persistent_conn(int4) * @ora_func: UTL_HTTP.CLOSE_PERSISTENT_CONN(CONN PL/SQL_RECORD) */ Datum utl_http_close_persistent_conn(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } /* * @qdb_func: utl_http_close_persistent_conns(text, int4, text, int4, boolean) * @ora_func: UTL_HTTP.CLOSE_PERSISTENT_CONNS(VARCHAR2, BINARY_INTEGER, VARCHAR2, BINARY_INTEGER, BOOLEAN) */ Datum utl_http_close_persistent_conns(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } // ---------- REQUEST CONTEXT ---------- /* * @qdb_func: utl_http_create_request_context(text, text, boolean, int4, int4) * @ora_func: UTL_HTTP.CREATE_REQUEST_CONTEXT(VARCHAR2, VARCHAR2, BOOLEAN, BINARY_INTEGER, BINARY_INTEGER) */ Datum utl_http_create_request_context(PG_FUNCTION_ARGS) { PG_RETURN_INT32(1); } /* * @qdb_func: utl_http_destroy_request_context(int4) * @ora_func: UTL_HTTP.DESTROY_REQUEST_CONTEXT(BINARY_INTEGER) */ Datum utl_http_destroy_request_context(PG_FUNCTION_ARGS) { PG_RETURN_NULL(); } // ---------- DIAGNOSTICS ---------- /* * @qdb_func: utl_http_get_detailed_sqlcode() * @ora_func: UTL_HTTP.GET_DETAILED_SQLCODE() */ Datum utl_http_get_detailed_sqlcode(PG_FUNCTION_ARGS) { PG_RETURN_INT32(0); } /* * @qdb_func: utl_http_get_detailed_sqlerrm() * @ora_func: UTL_HTTP.GET_DETAILED_SQLERRM() */ Datum utl_http_get_detailed_sqlerrm(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text("")); } Datum utl_http_get_response_error_check_fn(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(g_resp_error_check); } Datum utl_http_get_detailed_excp_support_fn(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(false); } /// @brief Возвращает версию RUDB пакета UTL_HTTP (Oracle UTL_HTTP пакет) Datum utl_http_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_UTL_HTTP_VERSION)); } } // extern "C"