#include "dbms/owa.h" #include extern "C" { #include "access/xact.h" #include "catalog/pg_type_d.h" #include "pgtime.h" #include "utils/array.h" #include "utils/builtins.h" #include "utils/elog.h" #include "utils/timestamp.h" } namespace Owa { PageContext *current_page_context_ = nullptr; bool subxact_callback_registered_ = false; bool xact_callback_registered_ = false; std::string textToString(text *value) { char *rawText = nullptr; std::string converted; rawText = text_to_cstring(value); converted = rawText; pfree(rawText); return converted; } static const char * weekday3(int weekday) { static const char *names[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; if (weekday < 0 || weekday > 6) { return "Sun"; } return names[weekday]; } static const char * month3(int month) { static const char *names[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; if (month < 0 || month > 11) { return "Jan"; } return names[month]; } static void checkNoCrlf(const std::string &arg_value, const char *arg_name) { if (arg_value.find('\r') != std::string::npos || arg_value.find('\n') != std::string::npos) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid character in %s", arg_name), errdetail("HTTP header values must not contain CR or LF."))); } } static void checkAsciiHeader(const std::string &arg_value, const char *arg_name) { for (unsigned char ch : arg_value) { if (ch < 0x20 || ch > 0x7E) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid character in %s", arg_name), errdetail("HTTP headers must be ASCII and printable."))); } } } void validateHeaderValue(const std::string &arg_value, const char *arg_name) { checkNoCrlf(arg_value, arg_name); checkAsciiHeader(arg_value, arg_name); } void validateCookieName(const std::string &cookie_name) { if (cookie_name.empty()) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("cookie name must not be empty"))); } validateHeaderValue(cookie_name, "name"); if (cookie_name.find(' ') != std::string::npos || cookie_name.find(';') != std::string::npos || cookie_name.find(',') != std::string::npos || cookie_name.find('=') != std::string::npos) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid cookie name"), errdetail("Cookie name must not contain spaces, ';', ',' or '='."))); } } std::string normalizeCgiName(const std::string &cgi_name) { std::string normalizedName; normalizedName.reserve(cgi_name.size()); for (unsigned char ch : cgi_name) { normalizedName.push_back(pg_toupper(ch)); } return normalizedName; } static void applyCacheCgiValue(PageContext *ctx, const std::string &cgi_name, const std::string &cgi_value) { std::string normalizedName; normalizedName = normalizeCgiName(cgi_name); ctx->cgiValues[normalizedName] = cgi_value; if (normalizedName == "OWA_CACHE_ETAG" || normalizedName == "HTTP_IF_NONE_MATCH") { validateCacheEtag(cgi_value); ctx->hasRequestCacheEtag = true; ctx->requestCacheEtag = cgi_value; return; } if (normalizedName == "OWA_CACHE_LEVEL" || normalizedName == "HTTP_OWA_CACHE_LEVEL") { ctx->hasRequestCacheLevel = true; ctx->requestCacheLevel = validateAndNormalizeCacheLevel(cgi_value); return; } if (normalizedName == "REQUEST_PROTOCOL") { validateHeaderValue(cgi_value, "request_protocol"); ctx->hasRequestProtocol = true; ctx->requestProtocol = cgi_value; return; } } static std::string renderStatusLine(int32 status_code, const std::string &status_reason) { std::string out; out.reserve(status_reason.size() + 24); out += "Status: "; out += std::to_string(status_code); if (!status_reason.empty()) { out += " "; out += status_reason; } out += "\n"; return out; } static std::string formatCookieExpires(TimestampTz ts) { pg_time_t utcTime; struct pg_tm *tm = nullptr; char outBuffer[128]; utcTime = timestamptz_to_time_t(ts); tm = pg_gmtime(&utcTime); if (tm == nullptr) { return "Thu, 01-Jan-1970 00:00:00 GMT"; } snprintf(outBuffer, sizeof(outBuffer), "%s, %02d-%s-%04d %02d:%02d:%02d GMT", weekday3(tm->tm_wday), tm->tm_mday, month3(tm->tm_mon), tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); return std::string(outBuffer); } static std::string renderCookieLine(const CookieData &cookie) { std::string out; out.reserve(128); out += "Set-Cookie: "; out += cookie.name; out += "="; out += cookie.value; out += ";"; if (cookie.has_expires) { out += " expires="; out += formatCookieExpires(cookie.expires); out += ";"; } if (cookie.has_path) { out += " path="; out += cookie.path; out += ";"; } if (cookie.has_domain) { out += " domain="; out += cookie.domain; out += ";"; } if (cookie.has_secure) { out += " secure;"; } return out; } void resetPageContext(void) { if (current_page_context_ == nullptr) { return; } delete current_page_context_; current_page_context_ = nullptr; } static void xactCallback(XactEvent event, void *arg) { (void) arg; if (event == XACT_EVENT_PRE_COMMIT || event == XACT_EVENT_PARALLEL_PRE_COMMIT || event == XACT_EVENT_PRE_PREPARE || event == XACT_EVENT_PREPARE) { return; } resetPageContext(); } static void subxactCallback(SubXactEvent event, SubTransactionId my_subid, SubTransactionId parent_subid, void *arg) { PageContext *ctx = current_page_context_; std::vector newEvents; (void) parent_subid; (void) arg; if (ctx == nullptr) { return; } if (event != SUBXACT_EVENT_ABORT_SUB) { return; } newEvents.reserve(ctx->events.size()); for (const auto &ev : ctx->events) { if (ev.subxid == my_subid) { continue; } newEvents.push_back(ev); } ctx->events.swap(newEvents); } void ensureCallbackRegistered(void) { if (!xact_callback_registered_) { RegisterXactCallback(xactCallback, nullptr); xact_callback_registered_ = true; } if (!subxact_callback_registered_) { RegisterSubXactCallback(subxactCallback, nullptr); subxact_callback_registered_ = true; } } void ensurePageContextViaServiceInit(void) { if (current_page_context_ != nullptr) { return; } { LOCAL_FCINFO(fcinfo2, 4); InitFunctionCallInfoData(*fcinfo2, nullptr, 4, InvalidOid, nullptr, nullptr); fcinfo2->args[0].value = Int32GetDatum(0); fcinfo2->args[0].isnull = false; fcinfo2->args[1].value = (Datum) 0; fcinfo2->args[1].isnull = true; fcinfo2->args[2].value = (Datum) 0; fcinfo2->args[2].isnull = true; fcinfo2->args[3].value = Int32GetDatum(0); fcinfo2->args[3].isnull = false; (void) owa_init_cgi_env2(fcinfo2); } } void appendHtpText(const char *text, bool add_new_line) { PageContext *ctx = current_page_context_; EventEntry ev; if (ctx == nullptr) { return; } if (ctx->state == PageState::HeadersOpen) { ctx->state = PageState::BodyStarted; } ev.kind = EventKind::BodyText; ev.subxid = GetCurrentSubTransactionId(); if (text != nullptr) { ev.bodyText = text; } if (add_new_line) { ev.bodyText.push_back('\n'); } ctx->events.push_back(ev); } static std::string renderShowpageAndReset(void) { PageContext *ctx = current_page_context_; std::string out; bool cacheDisabled = false; if (ctx == nullptr) { return out; } for (const auto &ev : ctx->events) { if (ev.kind == EventKind::Cache && ev.cacheDisabled) { cacheDisabled = true; break; } } for (const auto &ev : ctx->events) { if (ev.kind == EventKind::BodyText) { out += ev.bodyText; continue; } if (ev.kind == EventKind::Cookie) { out += renderCookieLine(ev.cookieData); out.push_back('\n'); continue; } if (ev.kind == EventKind::Cache) { if (cacheDisabled) { continue; } if (!ev.cacheSurrogateControl.empty()) { out += "Surrogate-Control: "; out += ev.cacheSurrogateControl; out += "\n"; } else if (!ev.cacheEtag.empty()) { out += renderCacheHeaders(ev.cacheEtag, ev.cacheLevel); } else { out += renderExpiresHeaders(ev.cacheExpires, ev.cacheLevel); } continue; } if (ev.kind == EventKind::Status) { out += renderStatusLine(ev.statusCode, ev.statusReason); continue; } } ctx->events.clear(); ctx->state = PageState::HeadersOpen; return out; } } /* namespace Owa */ extern "C" { PG_FUNCTION_INFO_V1(owa_init_cgi_env); PG_FUNCTION_INFO_V1(owa_init_cgi_env2); PG_FUNCTION_INFO_V1(owa_cookie_send); PG_FUNCTION_INFO_V1(owa_cookie_send2); PG_FUNCTION_INFO_V1(owa_util_get_cgi_env); PG_FUNCTION_INFO_V1(owa_util_showpage); PG_FUNCTION_INFO_V1(owa_util_showpage_utils); Datum owa_init_cgi_env(PG_FUNCTION_ARGS) { int32 cgiCount = 0; ArrayType *_nameArray = nullptr; ArrayType *_valueArray = nullptr; Datum *nameValues = nullptr; Datum *valueValues = nullptr; bool *nameNulls = nullptr; bool *valueNulls = nullptr; int nameCount = 0; int valueCount = 0; int processedCount = 0; int ignoredCount = 0; (void) fcinfo; Owa::resetPageContext(); Owa::current_page_context_ = new Owa::PageContext(); Owa::ensureCallbackRegistered(); if (PG_NARGS() != 0 && PG_NARGS() != 3) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("OWA.INIT_CGI_ENV accepts either 0 or 3 arguments"))); } if (PG_NARGS() == 3) { if (PG_ARGISNULL(0)) { ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("OWA.INIT_CGI_ENV parameter num_cgi_vars must not be NULL"))); } cgiCount = PG_GETARG_INT32(0); if (cgiCount < 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("OWA.INIT_CGI_ENV parameter num_cgi_vars must be zero or greater"))); } if (cgiCount > 0 && (PG_ARGISNULL(1) || PG_ARGISNULL(2))) { ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("OWA.INIT_CGI_ENV parameters param_name and param_val must not be NULL when num_cgi_vars is greater than zero"))); } if (!PG_ARGISNULL(1)) { _nameArray = PG_GETARG_ARRAYTYPE_P(1); if (ARR_NDIM(_nameArray) > 1) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("OWA.INIT_CGI_ENV parameter param_name must be a one-dimensional text array"))); } if (ARR_NDIM(_nameArray) > 0) { deconstruct_array(_nameArray, TEXTOID, -1, false, 'i', &nameValues, &nameNulls, &nameCount); } } if (!PG_ARGISNULL(2)) { _valueArray = PG_GETARG_ARRAYTYPE_P(2); if (ARR_NDIM(_valueArray) > 1) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("OWA.INIT_CGI_ENV parameter param_val must be a one-dimensional text array"))); } if (ARR_NDIM(_valueArray) > 0) { deconstruct_array(_valueArray, TEXTOID, -1, false, 'i', &valueValues, &valueNulls, &valueCount); } } if (nameCount < cgiCount || valueCount < cgiCount) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("OWA.INIT_CGI_ENV arrays are shorter than num_cgi_vars"), errdetail("num_cgi_vars=%d, param_name_count=%d, param_val_count=%d", cgiCount, nameCount, valueCount))); } for (int itemIndex = 0; itemIndex < cgiCount; ++itemIndex) { std::string nameValue; std::string valueValue; bool etagBefore; bool levelBefore; if ((nameNulls != nullptr && nameNulls[itemIndex]) || (valueNulls != nullptr && valueNulls[itemIndex])) { ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("OWA.INIT_CGI_ENV CGI name/value items must not be NULL"), errdetail("item_index=%d", itemIndex + 1))); } nameValue = Owa::textToString(DatumGetTextPP(nameValues[itemIndex])); valueValue = Owa::textToString(DatumGetTextPP(valueValues[itemIndex])); Owa::validateHeaderValue(nameValue, "param_name"); Owa::validateHeaderValue(valueValue, "param_val"); etagBefore = Owa::current_page_context_->hasRequestCacheEtag; levelBefore = Owa::current_page_context_->hasRequestCacheLevel; Owa::applyCacheCgiValue(Owa::current_page_context_, nameValue, valueValue); if ((!etagBefore && Owa::current_page_context_->hasRequestCacheEtag) || (!levelBefore && Owa::current_page_context_->hasRequestCacheLevel) || (etagBefore && Owa::normalizeCgiName(nameValue) == "OWA_CACHE_ETAG") || (etagBefore && Owa::normalizeCgiName(nameValue) == "HTTP_IF_NONE_MATCH") || (levelBefore && Owa::normalizeCgiName(nameValue) == "OWA_CACHE_LEVEL") || (levelBefore && Owa::normalizeCgiName(nameValue) == "HTTP_OWA_CACHE_LEVEL")) { ++processedCount; } else { ++ignoredCount; } } if (nameValues != nullptr) { pfree(nameValues); } if (valueValues != nullptr) { pfree(valueValues); } if (nameNulls != nullptr) { pfree(nameNulls); } if (valueNulls != nullptr) { pfree(valueNulls); } } ereport(LOG, (errmsg("OWA.INIT_CGI_ENV initialized request context"), errdetail("nargs=%d, num_cgi_vars=%d, recognized_cache_items=%d, ignored_items=%d, request_cache_etag=%s, request_cache_level=%s, request_protocol=%s", PG_NARGS(), cgiCount, processedCount, ignoredCount, Owa::current_page_context_->hasRequestCacheEtag ? "present" : "absent", Owa::current_page_context_->hasRequestCacheLevel ? "present" : "absent", Owa::current_page_context_->hasRequestProtocol ? Owa::current_page_context_->requestProtocol.c_str() : "absent"))); PG_RETURN_VOID(); } Datum owa_init_cgi_env2(PG_FUNCTION_ARGS) { int32 serviceArg = 0; if (PG_NARGS() != 4) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("OWA.INIT_CGI_ENV2 accepts exactly 4 arguments"))); } if (!PG_ARGISNULL(3)) { serviceArg = PG_GETARG_INT32(3); } (void) serviceArg; { LOCAL_FCINFO(fcinfo2, 3); InitFunctionCallInfoData(*fcinfo2, nullptr, 3, InvalidOid, nullptr, nullptr); fcinfo2->args[0].value = PG_GETARG_DATUM(0); fcinfo2->args[0].isnull = PG_ARGISNULL(0); fcinfo2->args[1].value = PG_GETARG_DATUM(1); fcinfo2->args[1].isnull = PG_ARGISNULL(1); fcinfo2->args[2].value = PG_GETARG_DATUM(2); fcinfo2->args[2].isnull = PG_ARGISNULL(2); (void) owa_init_cgi_env(fcinfo2); } PG_RETURN_VOID(); } Datum owa_cookie_send(PG_FUNCTION_ARGS) { Owa::CookieData cookieData; std::string secureValue; Owa::EventEntry ev; Owa::PageContext *ctx = Owa::current_page_context_; bool isNullName = false; bool isNullValue = false; if (ctx == nullptr) { Owa::ensurePageContextViaServiceInit(); ctx = Owa::current_page_context_; } if (ctx->state != Owa::PageState::HeadersOpen) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("OWA_COOKIE.SEND must be called in HTTP header context"))); } isNullName = PG_ARGISNULL(0); isNullValue = PG_ARGISNULL(1); cookieData.name = isNullName ? "" : Owa::textToString(PG_GETARG_TEXT_PP(0)); cookieData.value = isNullValue ? "" : Owa::textToString(PG_GETARG_TEXT_PP(1)); if (!isNullName) { Owa::validateCookieName(cookieData.name); } Owa::validateHeaderValue(cookieData.value, "value"); if (PG_NARGS() > 2 && !PG_ARGISNULL(2)) { cookieData.has_expires = true; cookieData.expires = PG_GETARG_TIMESTAMPTZ(2); } if (PG_NARGS() > 3 && !PG_ARGISNULL(3)) { cookieData.has_path = true; cookieData.path = Owa::textToString(PG_GETARG_TEXT_PP(3)); Owa::validateHeaderValue(cookieData.path, "path"); } if (PG_NARGS() > 4 && !PG_ARGISNULL(4)) { cookieData.has_domain = true; cookieData.domain = Owa::textToString(PG_GETARG_TEXT_PP(4)); Owa::validateHeaderValue(cookieData.domain, "domain"); } if (PG_NARGS() > 5 && !PG_ARGISNULL(5)) { secureValue = Owa::textToString(PG_GETARG_TEXT_PP(5)); Owa::validateHeaderValue(secureValue, "secure"); cookieData.has_secure = true; } ev.kind = Owa::EventKind::Cookie; ev.subxid = GetCurrentSubTransactionId(); ev.cookieData = std::move(cookieData); ctx->events.push_back(std::move(ev)); PG_RETURN_VOID(); } Datum owa_cookie_send2(PG_FUNCTION_ARGS) { int32 serviceArg = 0; if (PG_NARGS() != 7) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("OWA_COOKIE.SEND2 accepts exactly 7 arguments"))); } if (!PG_ARGISNULL(6)) { serviceArg = PG_GETARG_INT32(6); } (void) serviceArg; { LOCAL_FCINFO(fcinfo2, 6); InitFunctionCallInfoData(*fcinfo2, nullptr, 6, InvalidOid, nullptr, nullptr); fcinfo2->args[0].value = PG_GETARG_DATUM(0); fcinfo2->args[0].isnull = PG_ARGISNULL(0); fcinfo2->args[1].value = PG_GETARG_DATUM(1); fcinfo2->args[1].isnull = PG_ARGISNULL(1); fcinfo2->args[2].value = PG_GETARG_DATUM(2); fcinfo2->args[2].isnull = PG_ARGISNULL(2); fcinfo2->args[3].value = PG_GETARG_DATUM(3); fcinfo2->args[3].isnull = PG_ARGISNULL(3); fcinfo2->args[4].value = PG_GETARG_DATUM(4); fcinfo2->args[4].isnull = PG_ARGISNULL(4); fcinfo2->args[5].value = PG_GETARG_DATUM(5); fcinfo2->args[5].isnull = PG_ARGISNULL(5); (void) owa_cookie_send(fcinfo2); } PG_RETURN_VOID(); } Datum owa_util_get_cgi_env(PG_FUNCTION_ARGS) { Owa::PageContext *ctx = Owa::current_page_context_; std::string paramName; std::string normalizedName; auto cgiIt = ctx == nullptr ? Owa::PageContext().cgiValues.end() : ctx->cgiValues.end(); if (PG_NARGS() < 1 || PG_ARGISNULL(0)) { ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("OWA_UTIL.GET_CGI_ENV parameter param_name must not be NULL"))); } paramName = Owa::textToString(PG_GETARG_TEXT_PP(0)); normalizedName = Owa::normalizeCgiName(paramName); ereport(LOG, (errmsg("OWA_UTIL.GET_CGI_ENV request"), errdetail("param_name=\"%s\", normalized_name=\"%s\", ctx=%s", paramName.c_str(), normalizedName.c_str(), ctx == nullptr ? "null" : "present"))); if (ctx == nullptr) { ereport(LOG, (errmsg("OWA_UTIL.GET_CGI_ENV result"), errdetail("value=null, reason=no active OWA page context"))); PG_RETURN_NULL(); } cgiIt = ctx->cgiValues.find(normalizedName); if (cgiIt == ctx->cgiValues.end()) { ereport(LOG, (errmsg("OWA_UTIL.GET_CGI_ENV result"), errdetail("value=null, reason=cgi variable not found"))); PG_RETURN_NULL(); } ereport(LOG, (errmsg("OWA_UTIL.GET_CGI_ENV result"), errdetail("value=\"%s\"", cgiIt->second.c_str()))); PG_RETURN_TEXT_P(cstring_to_text(cgiIt->second.c_str())); } Datum owa_util_showpage(PG_FUNCTION_ARGS) { std::string renderedText = Owa::renderShowpageAndReset(); (void) fcinfo; if (!renderedText.empty()) { ereport(NOTICE, (errmsg("%s", renderedText.c_str()))); } PG_RETURN_VOID(); } Datum owa_util_showpage_utils(PG_FUNCTION_ARGS) { int32 serviceArg = 0; if (PG_NARGS() != 1) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("OWA_UTIL.SHOWPAGE_UTILS accepts exactly 1 argument"))); } if (!PG_ARGISNULL(0)) { serviceArg = PG_GETARG_INT32(0); } (void) serviceArg; { LOCAL_FCINFO(fcinfo2, 0); InitFunctionCallInfoData(*fcinfo2, nullptr, 0, InvalidOid, nullptr, nullptr); (void) owa_util_showpage(fcinfo2); } PG_RETURN_VOID(); } } /* extern "C" */