extern "C" { #include "postgres.h" #include "fmgr.h" #include "utils/builtins.h" #include "utils/varlena.h" #include "catalog/pg_type.h" } #include #include #include #include PG_MODULE_MAGIC; extern "C" { PG_FUNCTION_INFO_V1(utl_encode_base64_encode); PG_FUNCTION_INFO_V1(utl_encode_base64_decode); PG_FUNCTION_INFO_V1(utl_encode_base64_decode_internal); PG_FUNCTION_INFO_V1(utl_encode_quoted_printable_encode); PG_FUNCTION_INFO_V1(utl_encode_quoted_printable_decode); PG_FUNCTION_INFO_V1(utl_encode_mimeheader_encode); PG_FUNCTION_INFO_V1(utl_encode_mimeheader_decode); PG_FUNCTION_INFO_V1(utl_encode_text_encode); PG_FUNCTION_INFO_V1(utl_encode_text_decode); PG_FUNCTION_INFO_V1(utl_encode_uuencode); PG_FUNCTION_INFO_V1(utl_encode_uudecode); /* Доп. перегрузки для консоли DBEAVER-LIKE PG_FUNCTION_INFO_V1(utl_encode_base64_decode_vc); PG_FUNCTION_INFO_V1(utl_encode_quoted_printable_decode_vc); PG_FUNCTION_INFO_V1(utl_encode_uudecode_vc); */ PG_FUNCTION_INFO_V1(utl_encode_get_version); /// @brief Версия RUDB пакета UTL_ENCODE (Oracle UTL_ENCODE пакет) #define RUDB_UTL_ENCODE_VERSION "1.0.0" } namespace { /// @brief Конвертирует Datum bytea в std::string байтов через byteaout и парсинг "\\x…". inline std::string bytea_to_bytes(Datum d) { // byteaout возвращает C-строку в hex-формате: "\\xDEADBEEF" char* out = (char*) DirectFunctionCall1(byteaout, d); if (!out) return {}; std::string s(out); pfree(out); if (s.size() < 2 || !(s[0] == '\\' && s[1] == 'x')) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("UTL_ENCODE: unexpected byteaout format"))); std::string bytes; bytes.reserve((s.size() - 2) / 2); auto hexv = [](char ch)->int{ if (ch>='0'&&ch<='9') return ch-'0'; if (ch>='A'&&ch<='F') return 10+(ch-'A'); if (ch>='a'&&ch<='f') return 10+(ch-'a'); return -1; }; for (size_t i=2;i+1>4]); hex.push_back(hexdigits[b&0xF]); } char* c = pstrdup(hex.c_str()); Datum res = DirectFunctionCall1(byteain, CStringGetDatum(c)); return res; } /// @brief Преобразует PostgreSQL text* в std::string без перекодировки. inline std::string text_to_std_string(text* t) { char* c = text_to_cstring(t); std::string s(c); pfree(c); return s; } /// @brief Упаковывает std::string в PostgreSQL text* (Datum). inline Datum std_string_to_text(const std::string& s) { return PointerGetDatum(cstring_to_text_with_len(s.data(), (int)s.size())); } /// hex → nibble (0..15), или -1 inline int hex_nibble(unsigned char ch){ if (ch>='0'&&ch<='9') return ch-'0'; if (ch>='A'&&ch<='F') return 10+(ch-'A'); if (ch>='a'&&ch<='f') return 10+(ch-'a'); return -1; } inline bool looks_like_ascii_hex(const std::string& s){ if (s.size()<2 || (s.size()&1)) return false; for (unsigned char c: s) if (hex_nibble(c)<0) return false; return true; } inline std::string coerce_hex_ascii_to_bytes(const std::string& maybe_hex){ if (!looks_like_ascii_hex(maybe_hex)) return maybe_hex; std::string out; out.reserve(maybe_hex.size()/2); for (size_t i=0;i>2]); out.push_back(B64_TABLE[((a&3)<<4)|(b>>4)]); out.push_back(B64_TABLE[((b&0xF)<<2)|(c>>6)]); out.push_back(B64_TABLE[c&0x3F]); } size_t rem=in.size()-i; if (rem==1){ unsigned a=(unsigned char)in[i++]; out.push_back(B64_TABLE[a>>2]); out.push_back(B64_TABLE[(a&3)<<4]); out.push_back('='); out.push_back('='); } else if (rem==2){ unsigned a=(unsigned char)in[i++], b=(unsigned char)in[i++]; out.push_back(B64_TABLE[a>>2]); out.push_back(B64_TABLE[((a&3)<<4)|(b>>4)]); out.push_back(B64_TABLE[(b&0xF)<<2]); out.push_back('='); } return out; } inline std::string base64_decode_bytes(const std::string& in_raw) { std::string in; in.reserve(in_raw.size()); for (unsigned char ch: in_raw){ if (ch==' '||ch=='\t'||ch=='\r'||ch=='\n') continue; in.push_back((char)ch); } int8_t inv[256]; std::fill(std::begin(inv), std::end(inv), (int8_t)-1); for (int i=0;i<64;++i) inv[(unsigned char)B64_TABLE[i]]=(int8_t)i; inv[(unsigned char)'=']=-2; if (in.size()%4!=0) ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("UTL_ENCODE.BASE64_DECODE: input length not multiple of 4"))); std::string out; out.reserve((in.size()/4)*3); for (size_t i=0;i=0?(unsigned)c:0)<<6)|((d>=0?(unsigned)d:0)); out.push_back((char)((x>>16)&0xFF)); if (in[i+2]!='=') out.push_back((char)((x>>8)&0xFF)); if (in[i+3]!='=') out.push_back((char)(x&0xFF)); if (in[i+2]=='=' && in[i+3]!='=') ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("UTL_ENCODE.BASE64_DECODE: invalid padding"))); } return out; } // ---------- Quoted-Printable ---------- inline bool is_qp_printable(unsigned char c){ if (c=='=') return false; if (c==9 || c==32) return true; if (c>=33 && c<=60) return true; if (c>=62 && c<=126) return true; return false; } inline char hex_up(unsigned v){ static const char* k="0123456789ABCDEF"; return k[v&0xF]; } inline std::string qp_encode(const std::string& in) { std::string out; out.reserve(in.size()*3); for (size_t i=0;i='A'&&ch<='F') return 10+(ch-'A'); if (ch>='a'&&ch<='f') return 10+(ch-'a'); return -1; } inline std::string qp_decode(const std::string& in, bool header_variant=false) { std::string out; out.reserve(in.size()); for (size_t i=0;i=in.size()){ out.push_back('='); break; } unsigned char c1=(unsigned char)in[i+1]; if (c1=='\r'||c1=='\n'){ if (c1=='\r' && i+2=0 && h2>=0){ out.push_back((char)((h1<<4)|h2)); i+=2; continue; } } out.push_back('='); } return out; } // ---------- RFC 2047 (MIME header) ---------- inline bool starts_with(const std::string& s,const char* pfx){ size_t n=strlen(pfx); return s.size()>=n && memcmp(s.data(),pfx,n)==0; } inline std::string mimeheader_encode(const std::string& text,const std::string& charset,bool use_base64) { std::string enc = use_base64 ? base64_encode_bytes(text) : qp_encode(text); // header-qp ниже if (!use_base64){ // Q-variant: space->'_', '_'->=5F, CR/LF кодировать std::string tmp; tmp.reserve(enc.size()*2); for (size_t i=0;i(45, in.size()-i); out.push_back((char)uu_enc6((unsigned)n)); for (size_t j=0;j>2)&0x3F; unsigned t2=((a&3)<<4)|((b>>4)&0xF); unsigned t3=((b&0xF)<<2)|((c>>6)&3); unsigned t4=c&0x3F; out.push_back((char)uu_enc6(t1)); out.push_back((char)uu_enc6(t2)); out.push_back((char)uu_enc6(t3)); out.push_back((char)uu_enc6(t4)); } out.push_back('\n'); i+=n; } out.push_back((char)uu_enc6(0)); out.push_back('\n'); out.append("end\n"); return out; } inline std::string uudecode_data_only(const std::string& in_ascii) { std::string out; out.reserve(in_ascii.size()); size_t p=0,n=in_ascii.size(); while (pq) ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("UTL_ENCODE.UUDECODE: truncated data line"))); size_t produced=0; for (size_t g=0; g>4); unsigned b2=((c2&0xF)<<4)|(c3>>2); unsigned b3=((c3&3)<<6)|c4; if (produced sextets; sextets.reserve(need_groups*4); for (size_t g=0; gin.size()) ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("UTL_ENCODE.UUDECODE: truncated line"))); unsigned c1=uu_dec6((unsigned char)in[q++]); unsigned c2=uu_dec6((unsigned char)in[q++]); unsigned c3=uu_dec6((unsigned char)in[q++]); unsigned c4=uu_dec6((unsigned char)in[q++]); sextets.push_back(c1); sextets.push_back(c2); sextets.push_back(c3); sextets.push_back(c4); } while (q>4); unsigned byte2=((b&0xF)<<4)|(c>>2); unsigned byte3=((c&3)<<6)|d; if (produced=in.size() || in.compare(p,3,"end")!=0) ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("UTL_ENCODE.UUDECODE: missing 'end'"))); return out; } // ---------- misc ---------- enum { ENC_BASE64=1, ENC_QP=2 }; inline int get_encoding_or_default(bool isnull,int32 val){ if (isnull) return ENC_QP; if (val==ENC_BASE64) return ENC_BASE64; if (val==ENC_QP) return ENC_QP; return ENC_QP; } } // namespace extern "C" { // --- BASE64 --- /* * @qdb_func: utl_encode_base64_encode(raw) * @ora_func: UTL_ENCODE.BASE64_ENCODE(RAW) */ Datum utl_encode_base64_encode(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); Datum d=PG_GETARG_DATUM(0); std::string bytes=bytea_to_bytes(d); bytes = coerce_hex_ascii_to_bytes(bytes); // имитация RAW литерала std::string b64=base64_encode_bytes(bytes); PG_RETURN_DATUM(bytes_to_bytea(b64)); // RAW (ASCII в байтах) } /* * @qdb_func: utl_encode_base64_decode(raw) * @ora_func: UTL_ENCODE.BASE64_DECODE(RAW) */ Datum utl_encode_base64_decode(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); Datum d=PG_GETARG_DATUM(0); LOCAL_FCINFO(local_fcinfo, 2); InitFunctionCallInfoData(*local_fcinfo, NULL, 2, PG_GET_COLLATION(), fcinfo->context, NULL); local_fcinfo->args[0].value = d; local_fcinfo->args[0].isnull = fcinfo->args[0].isnull; local_fcinfo->args[1].value = DatumGetBool(false); local_fcinfo->args[1].isnull = false; PG_RETURN_DATUM( (*utl_encode_base64_decode_internal) (local_fcinfo)); } Datum utl_encode_base64_decode_internal(PG_FUNCTION_ARGS) { bool onempty = false; if(!PG_ARGISNULL(1)){ onempty = PG_GETARG_BOOL(1); } if (PG_ARGISNULL(0)){ if(onempty){ std::string res = ""; PG_RETURN_DATUM(bytes_to_bytea(res)); } else PG_RETURN_NULL(); } Datum d=PG_GETARG_DATUM(0); std::string ascii_b64=bytea_to_bytes(d); ascii_b64 = coerce_hex_ascii_to_bytes(ascii_b64); std::string decoded=base64_decode_bytes(ascii_b64); PG_RETURN_DATUM(bytes_to_bytea(decoded)); // RAW } // --- QP --- /* * @qdb_func: utl_encode_quoted_printable_encode(raw) * @ora_func: UTL_ENCODE.QUOTED_PRINTABLE_ENCODE(RAW) */ Datum utl_encode_quoted_printable_encode(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); Datum d=PG_GETARG_DATUM(0); std::string bytes=bytea_to_bytes(d); bytes = coerce_hex_ascii_to_bytes(bytes); std::string enc=qp_encode(bytes); PG_RETURN_DATUM(bytes_to_bytea(enc)); // RAW } /* * @qdb_func: utl_encode_quoted_printable_decode(raw) * @ora_func: UTL_ENCODE.QUOTED_PRINTABLE_DECODE(RAW) */ Datum utl_encode_quoted_printable_decode(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); Datum d=PG_GETARG_DATUM(0); std::string qp_ascii=bytea_to_bytes(d); qp_ascii = coerce_hex_ascii_to_bytes(qp_ascii); std::string dec=qp_decode(qp_ascii,false); PG_RETURN_DATUM(bytes_to_bytea(dec)); // RAW } // --- MIME header (varchar2) --- /* * @qdb_func: utl_encode_mimeheader_encode(text, text, int4) * @ora_func: UTL_ENCODE.MIMEHEADER_ENCODE(VARCHAR2, VARCHAR2, BINARY_INTEGER) */ Datum utl_encode_mimeheader_encode(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); std::string buf=text_to_std_string(PG_GETARG_TEXT_PP(0)); std::string charset = PG_ARGISNULL(1)? std::string() : text_to_std_string(PG_GETARG_TEXT_PP(1)); int32 enc_in=0; bool enc_isnull=PG_ARGISNULL(2); if (!enc_isnull) enc_in=PG_GETARG_INT32(2); bool use_b64 = (get_encoding_or_default(enc_isnull,enc_in)==ENC_BASE64); std::string out=mimeheader_encode(buf,charset,use_b64); PG_RETURN_DATUM(std_string_to_text(out)); } /* * @qdb_func: utl_encode_mimeheader_decode(text) * @ora_func: UTL_ENCODE.MIMEHEADER_DECODE(VARCHAR2) */ Datum utl_encode_mimeheader_decode(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); std::string in=text_to_std_string(PG_GETARG_TEXT_PP(0)), out; if (mimeheader_try_decode(in,out)) PG_RETURN_DATUM(std_string_to_text(out)); PG_RETURN_DATUM(std_string_to_text(in)); } // --- TEXT (varchar2) --- /* * @qdb_func: utl_encode_text_encode(text, text, int4) * @ora_func: UTL_ENCODE.TEXT_ENCODE(VARCHAR2, VARCHAR2, BINARY_INTEGER) */ Datum utl_encode_text_encode(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); std::string buf=text_to_std_string(PG_GETARG_TEXT_PP(0)); int32 enc_in=0; bool enc_isnull=PG_ARGISNULL(2); if (!enc_isnull) enc_in=PG_GETARG_INT32(2); int enc=get_encoding_or_default(enc_isnull,enc_in); std::string out = (enc==ENC_BASE64) ? base64_encode_bytes(buf) : qp_encode(buf); PG_RETURN_DATUM(std_string_to_text(out)); } /* * @qdb_func: utl_encode_text_decode(text, text, int4) * @ora_func: UTL_ENCODE.TEXT_DECODE(VARCHAR2, VARCHAR2, BINARY_INTEGER) */ Datum utl_encode_text_decode(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); std::string buf=text_to_std_string(PG_GETARG_TEXT_PP(0)); int32 enc_in=0; bool enc_isnull=PG_ARGISNULL(2); if (!enc_isnull) enc_in=PG_GETARG_INT32(2); int enc=get_encoding_or_default(enc_isnull,enc_in); std::string out = (enc==ENC_BASE64) ? base64_decode_bytes(buf) : qp_decode(buf,false); PG_RETURN_DATUM(std_string_to_text(out)); } // --- UU --- /* * @qdb_func: utl_encode_uuencode(raw, int4, text, text) * @ora_func: UTL_ENCODE.UUENCODE(RAW, BINARY_INTEGER, VARCHAR2, VARCHAR2) */ Datum utl_encode_uuencode(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); Datum d=PG_GETARG_DATUM(0); std::string bytes=bytea_to_bytes(d); bytes = coerce_hex_ascii_to_bytes(bytes); int32 type = (PG_NARGS()>1 && !PG_ARGISNULL(1)) ? PG_GETARG_INT32(1) : 1; if (type!=1) ereport(ERROR,(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("UTL_ENCODE.UUENCODE: only type=1 (complete) is supported"))); std::string filename = (PG_NARGS()>2 && !PG_ARGISNULL(2)) ? text_to_std_string(PG_GETARG_TEXT_PP(2)) : ""; std::string perm = (PG_NARGS()>3 && !PG_ARGISNULL(3)) ? text_to_std_string(PG_GETARG_TEXT_PP(3)) : ""; std::string enc=uuencode_bytes(bytes,filename,perm); PG_RETURN_DATUM(bytes_to_bytea(enc)); // RAW } /* * @qdb_func: utl_encode_uudecode(raw) * @ora_func: UTL_ENCODE.UUDECODE(RAW) */ Datum utl_encode_uudecode(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); Datum d=PG_GETARG_DATUM(0); std::string ascii=bytea_to_bytes(d); std::string dec=uudecode_bytes(ascii); PG_RETURN_DATUM(bytes_to_bytea(dec)); // RAW } /* // --- Доп. перегрузки для консоли (varchar2 -> varchar2) --- Datum utl_encode_base64_decode_vc(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); std::string in=text_to_std_string(PG_GETARG_TEXT_PP(0)); in = coerce_hex_ascii_to_bytes(in); std::string bytes=base64_decode_bytes(in); PG_RETURN_DATUM(std_string_to_text(bytes)); } Datum utl_encode_quoted_printable_decode_vc(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); std::string in=text_to_std_string(PG_GETARG_TEXT_PP(0)); in = coerce_hex_ascii_to_bytes(in); std::string bytes=qp_decode(in,false); PG_RETURN_DATUM(std_string_to_text(bytes)); } Datum utl_encode_uudecode_vc(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); std::string in=text_to_std_string(PG_GETARG_TEXT_PP(0)); std::string bytes=uudecode_bytes(in); PG_RETURN_DATUM(std_string_to_text(bytes)); } */ /// @brief Возвращает версию RUDB пакета UTL_ENCODE (Oracle UTL_ENCODE пакет) Datum utl_encode_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_UTL_ENCODE_VERSION)); } } // extern "C"