#include <cctype>
|
#include <cstdio>
|
#include <cstring>
|
#include <string>
|
#include <vector>
|
#include <sys/stat.h>
|
|
extern "C"
|
{
|
#include "postgres.h"
|
#include "fmgr.h"
|
#include "funcapi.h"
|
#include "executor/spi.h"
|
#include "storage/fd.h"
|
#include "utils/builtins.h"
|
#include "utils/numeric.h"
|
#include "utils/lsyscache.h"
|
#include "miscadmin.h"
|
#include "catalog/namespace.h"
|
#include "catalog/pg_authid_d.h"
|
#include "utils/acl.h"
|
#include "dbms/dbms_java.h"
|
#include <zlib.h>
|
}
|
|
namespace DbmsJava
|
{
|
|
struct Piece
|
{
|
std::string shortName;
|
std::string longName;
|
std::string kind;
|
bytea *payload;
|
std::string derived;
|
std::string status;
|
};
|
|
static void
|
failJava(const char *text)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("%s", text)));
|
}
|
|
static void
|
failPerm(const char *path)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
|
errmsg("dbms_java: нет права чтения файла"),
|
errdetail_internal("Output: [Path: %s]", path)));
|
}
|
|
static std::string
|
textOrEmpty(Datum value, bool isnull)
|
{
|
if (isnull)
|
return std::string();
|
char *raw = text_to_cstring(DatumGetTextPP(value));
|
std::string out(raw);
|
pfree(raw);
|
return out;
|
}
|
|
static std::string
|
currentSchema()
|
{
|
List *path = fetch_search_path(false);
|
Oid nsp = linitial_oid(path);
|
list_free(path);
|
char *name = get_namespace_name(nsp);
|
std::string out(name != NULL ? name : "public");
|
if (name != NULL)
|
pfree(name);
|
return out;
|
}
|
|
static std::string
|
defaultResolver(const std::string &schema)
|
{
|
return std::string("((* ") + schema + ")(* public))";
|
}
|
|
static std::string
|
dotsToSlashes(const std::string &name)
|
{
|
std::string out = name;
|
for (size_t i = 0; i < out.size(); i++)
|
{
|
if (out[i] == '.')
|
out[i] = '/';
|
}
|
return out;
|
}
|
|
static std::string
|
slashesToDots(const std::string &name)
|
{
|
std::string out = name;
|
for (size_t i = 0; i < out.size(); i++)
|
{
|
if (out[i] == '/')
|
out[i] = '.';
|
}
|
return out;
|
}
|
|
static bytea *
|
copyBytes(const char *data, size_t len)
|
{
|
bytea *result = (bytea *) palloc(VARHDRSZ + len);
|
SET_VARSIZE(result, VARHDRSZ + len);
|
if (len > 0)
|
memcpy(VARDATA(result), data, len);
|
return result;
|
}
|
|
static bytea *
|
readFile(const char *path)
|
{
|
FILE *handle = AllocateFile(path, "rb");
|
if (handle == NULL)
|
{
|
if (errno == EACCES || errno == EPERM)
|
failPerm(path);
|
failJava("dbms_java: файл не открыт");
|
}
|
if (fseek(handle, 0, SEEK_END) != 0)
|
{
|
FreeFile(handle);
|
failJava("dbms_java: файл не прочитан");
|
}
|
long size = ftell(handle);
|
if (size < 0)
|
{
|
FreeFile(handle);
|
failJava("dbms_java: файл не прочитан");
|
}
|
if (fseek(handle, 0, SEEK_SET) != 0)
|
{
|
FreeFile(handle);
|
failJava("dbms_java: файл не прочитан");
|
}
|
bytea *payload = (bytea *) palloc(VARHDRSZ + (size_t) size);
|
SET_VARSIZE(payload, VARHDRSZ + (size_t) size);
|
if (size > 0 && fread(VARDATA(payload), 1, (size_t) size, handle) != (size_t) size)
|
{
|
FreeFile(handle);
|
failJava("dbms_java: файл не прочитан");
|
}
|
FreeFile(handle);
|
return payload;
|
}
|
|
static uint16
|
be16(const unsigned char *p)
|
{
|
return (uint16) ((p[0] << 8) | p[1]);
|
}
|
|
static uint32
|
be32(const unsigned char *p)
|
{
|
return ((uint32) p[0] << 24) | ((uint32) p[1] << 16) | ((uint32) p[2] << 8) | (uint32) p[3];
|
}
|
|
static uint16
|
ru16(const unsigned char *p)
|
{
|
return (uint16) (p[0] | (p[1] << 8));
|
}
|
|
static uint32
|
ru32(const unsigned char *p)
|
{
|
return (uint32) p[0] | ((uint32) p[1] << 8) | ((uint32) p[2] << 16) | ((uint32) p[3] << 24);
|
}
|
|
static std::string
|
classNameFromBytes(const unsigned char *data, size_t len)
|
{
|
if (len < 10 || be32(data) != 0xCAFEBABE)
|
failJava("dbms_java: повреждённый class-файл");
|
uint16 count = be16(data + 8);
|
size_t pos = 10;
|
std::vector<std::string> utf8(count);
|
std::vector<uint16> classIdx(count, 0);
|
for (uint16 i = 1; i < count; i++)
|
{
|
if (pos >= len)
|
failJava("dbms_java: повреждённый class-файл");
|
unsigned char tag = data[pos++];
|
if (tag == 1)
|
{
|
if (pos + 2 > len)
|
failJava("dbms_java: повреждённый class-файл");
|
uint16 n = be16(data + pos);
|
pos += 2;
|
if (pos + n > len)
|
failJava("dbms_java: повреждённый class-файл");
|
utf8[i].assign((const char *) data + pos, n);
|
pos += n;
|
}
|
else if (tag == 7 || tag == 8 || tag == 16 || tag == 19 || tag == 20)
|
{
|
if (pos + 2 > len)
|
failJava("dbms_java: повреждённый class-файл");
|
if (tag == 7)
|
classIdx[i] = be16(data + pos);
|
pos += 2;
|
}
|
else if (tag == 15)
|
pos += 3;
|
else if (tag == 3 || tag == 4 || tag == 9 || tag == 10 || tag == 11 || tag == 12 || tag == 17 || tag == 18)
|
pos += 4;
|
else if (tag == 5 || tag == 6)
|
{
|
pos += 8;
|
i++;
|
}
|
else
|
failJava("dbms_java: повреждённый class-файл");
|
}
|
if (pos + 4 > len)
|
failJava("dbms_java: повреждённый class-файл");
|
uint16 thisClass = be16(data + pos + 2);
|
if (thisClass == 0 || thisClass >= count || classIdx[thisClass] == 0 || classIdx[thisClass] >= count)
|
failJava("dbms_java: повреждённый class-файл");
|
return utf8[classIdx[thisClass]];
|
}
|
|
struct NcompMeth
|
{
|
std::string name;
|
std::string desc;
|
};
|
|
static bool
|
classMethodsFromBytes(const unsigned char *data, size_t len, std::vector<NcompMeth> *methods)
|
{
|
if (len < 10 || be32(data) != 0xCAFEBABE)
|
return false;
|
uint16 count = be16(data + 8);
|
size_t pos = 10;
|
std::vector<std::string> utf8(count);
|
for (uint16 i = 1; i < count; i++)
|
{
|
if (pos >= len)
|
return false;
|
unsigned char tag = data[pos++];
|
if (tag == 1)
|
{
|
if (pos + 2 > len)
|
return false;
|
uint16 n = be16(data + pos);
|
pos += 2;
|
if (pos + n > len)
|
return false;
|
utf8[i].assign((const char *) data + pos, n);
|
pos += n;
|
}
|
else if (tag == 7 || tag == 8 || tag == 16 || tag == 19 || tag == 20)
|
pos += 2;
|
else if (tag == 15)
|
pos += 3;
|
else if (tag == 3 || tag == 4 || tag == 9 || tag == 10 || tag == 11 || tag == 12 || tag == 17 || tag == 18)
|
pos += 4;
|
else if (tag == 5 || tag == 6)
|
{
|
pos += 8;
|
i++;
|
}
|
else
|
return false;
|
}
|
if (pos + 6 > len)
|
return false;
|
pos += 6;
|
if (pos + 2 > len)
|
return false;
|
uint16 ifaces = be16(data + pos);
|
pos += 2 + (size_t) ifaces * 2;
|
if (pos + 2 > len)
|
return false;
|
uint16 fields = be16(data + pos);
|
pos += 2;
|
for (uint16 f = 0; f < fields; f++)
|
{
|
if (pos + 8 > len)
|
return false;
|
pos += 6;
|
uint16 attrs = be16(data + pos);
|
pos += 2;
|
for (uint16 a = 0; a < attrs; a++)
|
{
|
if (pos + 6 > len)
|
return false;
|
uint32 alen = be32(data + pos + 2);
|
pos += 6 + alen;
|
}
|
}
|
if (pos + 2 > len)
|
return false;
|
uint16 nmethods = be16(data + pos);
|
pos += 2;
|
for (uint16 m = 0; m < nmethods; m++)
|
{
|
if (pos + 8 > len)
|
return false;
|
uint16 nameIdx = be16(data + pos + 2);
|
uint16 descIdx = be16(data + pos + 4);
|
pos += 6;
|
uint16 attrs = be16(data + pos);
|
pos += 2;
|
for (uint16 a = 0; a < attrs; a++)
|
{
|
if (pos + 6 > len)
|
return false;
|
uint32 alen = be32(data + pos + 2);
|
pos += 6 + alen;
|
}
|
NcompMeth meth;
|
if (nameIdx > 0 && nameIdx < count)
|
meth.name = utf8[nameIdx];
|
if (descIdx > 0 && descIdx < count)
|
meth.desc = utf8[descIdx];
|
methods->push_back(meth);
|
}
|
return true;
|
}
|
|
static bool
|
javaNames(const std::string &source, std::string *shortName, std::string *longName)
|
{
|
std::string pkg;
|
std::string cls;
|
size_t packPos = source.find("package ");
|
if (packPos != std::string::npos)
|
{
|
size_t i = packPos + 8;
|
while (i < source.size() && source[i] != ';')
|
{
|
if (source[i] != ' ' && source[i] != '\t' && source[i] != '\n' && source[i] != '\r')
|
pkg.push_back(source[i]);
|
i++;
|
}
|
}
|
size_t classPos = source.find("class ");
|
if (classPos == std::string::npos)
|
return false;
|
size_t i = classPos + 6;
|
while (i < source.size() && (source[i] == ' ' || source[i] == '\t'))
|
i++;
|
while (i < source.size() && (isalnum((unsigned char) source[i]) || source[i] == '_'))
|
{
|
cls.push_back(source[i]);
|
i++;
|
}
|
if (cls.empty())
|
return false;
|
if (pkg.empty())
|
{
|
*shortName = cls;
|
*longName = cls;
|
}
|
else
|
{
|
*shortName = dotsToSlashes(pkg) + "/" + cls;
|
*longName = pkg + "." + cls;
|
}
|
return true;
|
}
|
|
struct ZipItem
|
{
|
std::string name;
|
bytea *payload;
|
};
|
|
static bytea *
|
inflateRaw(const unsigned char *src, uint32 compLen, uint32 rawLen)
|
{
|
z_stream strm;
|
bytea *out;
|
int rc;
|
|
if (rawLen > 32 * 1024 * 1024)
|
failJava("dbms_java: jar слишком большой");
|
memset(&strm, 0, sizeof(strm));
|
if (inflateInit2(&strm, -15) != Z_OK)
|
failJava("dbms_java: jar не распакован");
|
out = (bytea *) palloc(VARHDRSZ + rawLen);
|
SET_VARSIZE(out, VARHDRSZ + rawLen);
|
strm.next_in = (Bytef *) src;
|
strm.avail_in = compLen;
|
strm.next_out = (Bytef *) VARDATA(out);
|
strm.avail_out = rawLen;
|
rc = inflate(&strm, Z_FINISH);
|
inflateEnd(&strm);
|
if (rc != Z_STREAM_END)
|
failJava("dbms_java: jar не распакован");
|
return out;
|
}
|
|
static std::vector<ZipItem>
|
jarItems(const unsigned char *data, size_t len, bool includeMeta)
|
{
|
std::vector<ZipItem> items;
|
if (len < 22)
|
return items;
|
size_t eocd = std::string::npos;
|
for (size_t i = len - 22; ; i--)
|
{
|
if (data[i] == 'P' && data[i + 1] == 'K' && data[i + 2] == 5 && data[i + 3] == 6)
|
{
|
eocd = i;
|
break;
|
}
|
if (i == 0)
|
break;
|
}
|
if (eocd == std::string::npos || eocd + 22 > len)
|
return items;
|
uint32 cdOff = ru32(data + eocd + 16);
|
uint16 entries = ru16(data + eocd + 10);
|
size_t pos = cdOff;
|
for (uint16 n = 0; n < entries; n++)
|
{
|
if (pos + 46 > len || ru32(data + pos) != 0x02014B50)
|
break;
|
uint16 method = ru16(data + pos + 10);
|
uint32 compLen = ru32(data + pos + 20);
|
uint32 rawLen = ru32(data + pos + 24);
|
uint16 nameLen = ru16(data + pos + 28);
|
uint16 extraLen = ru16(data + pos + 30);
|
uint16 commentLen = ru16(data + pos + 32);
|
uint32 localOff = ru32(data + pos + 42);
|
if (pos + 46 + nameLen > len)
|
break;
|
std::string name((const char *) data + pos + 46, nameLen);
|
pos += 46 + nameLen + extraLen + commentLen;
|
if (name.empty() || name.back() == '/')
|
continue;
|
if (!includeMeta && name.compare(0, 9, "META-INF/") == 0)
|
continue;
|
if (localOff + 30 > len || ru32(data + localOff) != 0x04034b50)
|
failJava("dbms_java: jar повреждён");
|
uint16 localName = ru16(data + localOff + 26);
|
uint16 localExtra = ru16(data + localOff + 28);
|
size_t dataOff = (size_t) localOff + 30 + localName + localExtra;
|
if (dataOff + compLen > len)
|
failJava("dbms_java: jar повреждён");
|
ZipItem item;
|
item.name = name;
|
if (method == 0)
|
item.payload = copyBytes((const char *) data + dataOff, rawLen);
|
else if (method == 8)
|
item.payload = inflateRaw(data + dataOff, compLen, rawLen);
|
else
|
failJava("dbms_java: jar повреждён");
|
items.push_back(item);
|
}
|
return items;
|
}
|
|
static void
|
upsert(const std::string &schema, const Piece &piece, const std::string &resolver)
|
{
|
Oid argtypes[8] = {TEXTOID, TEXTOID, TEXTOID, TEXTOID, BYTEAOID, TEXTOID, TEXTOID, TEXTOID};
|
Datum values[8];
|
char nulls[8] = {' ', ' ', ' ', ' ', 'n', ' ', 'n', ' '};
|
std::string status = piece.status.empty()
|
? (piece.kind == "resource" ? "VALID" : "INVALID")
|
: piece.status;
|
values[0] = CStringGetTextDatum(schema.c_str());
|
values[1] = CStringGetTextDatum(piece.shortName.c_str());
|
values[2] = CStringGetTextDatum(piece.longName.c_str());
|
values[3] = CStringGetTextDatum(piece.kind.c_str());
|
if (piece.payload != NULL)
|
{
|
values[4] = PointerGetDatum(piece.payload);
|
nulls[4] = ' ';
|
}
|
values[5] = CStringGetTextDatum(resolver.c_str());
|
if (!piece.derived.empty())
|
{
|
values[6] = CStringGetTextDatum(piece.derived.c_str());
|
nulls[6] = ' ';
|
}
|
values[7] = CStringGetTextDatum(status.c_str());
|
Oid keyTypes[3] = {TEXTOID, TEXTOID, TEXTOID};
|
Datum keyValues[3] = {values[0], values[1], values[3]};
|
char keyNulls[3] = {' ', ' ', ' '};
|
SPI_execute_with_args(
|
"DELETE FROM pg_catalog.dbms_java_object "
|
"WHERE schema_name = $1 AND short_name = $2 AND kind = $3",
|
3, keyTypes, keyValues, keyNulls, false, 0);
|
int rc = SPI_execute_with_args(
|
"INSERT INTO pg_catalog.dbms_java_object "
|
"(schema_name, short_name, long_name, kind, bytes, resolver, derived_from, status) "
|
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
|
8, argtypes, values, nulls, false, 0);
|
if (rc != SPI_OK_INSERT)
|
elog(ERROR, "dbms_java: запись каталога не выполнена");
|
}
|
|
static void
|
deleteNames(const std::string &schema, const std::vector<std::string> &shortNames)
|
{
|
for (size_t i = 0; i < shortNames.size(); i++)
|
{
|
Oid argtypes[2] = {TEXTOID, TEXTOID};
|
Datum values[2];
|
char nulls[2] = {' ', ' '};
|
values[0] = CStringGetTextDatum(schema.c_str());
|
values[1] = CStringGetTextDatum(shortNames[i].c_str());
|
SPI_execute_with_args(
|
"DELETE FROM pg_catalog.dbms_java_object "
|
"WHERE schema_name = $1 AND (short_name = $2 OR long_name = $2)",
|
2, argtypes, values, nulls, false, 0);
|
}
|
}
|
|
static std::vector<Piece>
|
piecesFromFile(const char *path, bytea *payload, bool resolve)
|
{
|
std::vector<Piece> pieces;
|
size_t len = VARSIZE(payload) - VARHDRSZ;
|
const unsigned char *data = (const unsigned char *) VARDATA(payload);
|
std::string pathText(path);
|
bool isJava = pathText.size() >= 5 && pathText.compare(pathText.size() - 5, 5, ".java") == 0;
|
bool isClass = pathText.size() >= 6 && pathText.compare(pathText.size() - 6, 6, ".class") == 0;
|
bool isJar = (pathText.size() >= 4 && pathText.compare(pathText.size() - 4, 4, ".jar") == 0) ||
|
(pathText.size() >= 4 && pathText.compare(pathText.size() - 4, 4, ".zip") == 0);
|
if (len == 0)
|
return pieces;
|
if (isJava)
|
{
|
std::string source((const char *) data, len);
|
std::string shortName;
|
std::string longName;
|
if (!javaNames(source, &shortName, &longName))
|
failJava("dbms_java: исходник без класса");
|
Piece src;
|
src.shortName = shortName;
|
src.longName = longName;
|
src.kind = "source";
|
src.payload = payload;
|
pieces.push_back(src);
|
Piece cls;
|
cls.shortName = shortName;
|
cls.longName = longName;
|
cls.kind = "class";
|
cls.payload = NULL;
|
cls.derived = shortName;
|
pieces.push_back(cls);
|
return pieces;
|
}
|
if (isClass)
|
{
|
std::string shortName = classNameFromBytes(data, len);
|
Piece cls;
|
cls.shortName = shortName;
|
cls.longName = slashesToDots(shortName);
|
cls.kind = "class";
|
cls.payload = payload;
|
pieces.push_back(cls);
|
return pieces;
|
}
|
if (isJar)
|
{
|
std::vector<ZipItem> entries = jarItems(data, len, resolve);
|
for (size_t i = 0; i < entries.size(); i++)
|
{
|
Piece piece;
|
const std::string &entry = entries[i].name;
|
if (entry.size() >= 6 && entry.compare(entry.size() - 6, 6, ".class") == 0)
|
{
|
piece.shortName = classNameFromBytes((const unsigned char *) VARDATA(entries[i].payload),
|
VARSIZE(entries[i].payload) - VARHDRSZ);
|
piece.longName = slashesToDots(piece.shortName);
|
piece.kind = "class";
|
piece.status = resolve ? "VALID" : "INVALID";
|
}
|
else
|
{
|
piece.shortName = entry;
|
piece.longName = entry;
|
piece.kind = "resource";
|
piece.status = "VALID";
|
}
|
piece.payload = entries[i].payload;
|
pieces.push_back(piece);
|
}
|
return pieces;
|
}
|
Piece res;
|
res.shortName = std::string("ROOT") + pathText;
|
res.longName = res.shortName;
|
res.kind = "resource";
|
res.status = "VALID";
|
res.payload = payload;
|
pieces.push_back(res);
|
return pieces;
|
}
|
|
struct Options
|
{
|
std::vector<std::string> files;
|
std::string resolver;
|
std::string schema;
|
bool resolve;
|
};
|
|
static Options
|
parseOptions(const std::string &text, const std::string &resolverArg, const std::string &schemaDefault)
|
{
|
if (text.empty())
|
failJava("dbms_java: пустые опции");
|
Options opt;
|
opt.resolver = resolverArg.empty() ? defaultResolver(schemaDefault) : resolverArg;
|
opt.schema = schemaDefault;
|
opt.resolve = false;
|
std::string token;
|
std::vector<std::string> tokens;
|
for (size_t i = 0; i <= text.size(); i++)
|
{
|
if (i == text.size() || text[i] == ' ' || text[i] == '\t' || text[i] == '\n' || text[i] == '\r')
|
{
|
if (!token.empty())
|
{
|
tokens.push_back(token);
|
token.clear();
|
}
|
}
|
else
|
token.push_back(text[i]);
|
}
|
if (tokens.empty())
|
failJava("dbms_java: пустые опции");
|
for (size_t i = 0; i < tokens.size(); i++)
|
{
|
const std::string &tok = tokens[i];
|
if (tok == "-thin" || tok == "-oci")
|
failJava("dbms_java: опция клиента не поддерживается");
|
if (tok == "-user" || tok == "-password")
|
{
|
if (i + 1 < tokens.size())
|
i++;
|
continue;
|
}
|
if (tok == "-schema")
|
{
|
if (i + 1 < tokens.size())
|
opt.schema = tokens[++i];
|
continue;
|
}
|
if (tok == "-resolve")
|
{
|
opt.resolve = true;
|
continue;
|
}
|
if (tok == "-resolver")
|
{
|
if (i + 1 < tokens.size())
|
opt.resolver = tokens[++i];
|
continue;
|
}
|
if (!tok.empty() && tok[0] == '-')
|
continue;
|
opt.files.push_back(tok);
|
}
|
return opt;
|
}
|
|
static void
|
loadOne(const std::string &schema, const std::string &resolver, const std::string &path, bool resolve)
|
{
|
if (path.empty() || path[0] != '/')
|
failPerm(path.c_str());
|
struct stat st;
|
if (stat(path.c_str(), &st) != 0)
|
{
|
if (errno == EACCES || errno == EPERM)
|
failPerm(path.c_str());
|
failJava("dbms_java: файл не найден");
|
}
|
if (!S_ISREG(st.st_mode))
|
failJava("dbms_java: это не файл");
|
bytea *payload = readFile(path.c_str());
|
std::vector<Piece> pieces = piecesFromFile(path.c_str(), payload, resolve);
|
if (resolve)
|
{
|
std::vector<Piece> extras;
|
for (size_t i = 0; i < pieces.size(); i++)
|
{
|
if (pieces[i].kind == "class" && pieces[i].payload != NULL)
|
pieces[i].status = "VALID";
|
if (pieces[i].kind != "source" || pieces[i].payload == NULL)
|
continue;
|
int slen = VARSIZE(pieces[i].payload) - VARHDRSZ;
|
std::string sourceName = pieces[i].shortName;
|
DbmsJavaCompiled *compiled = NULL;
|
int ncls = rudb_java_compile_classes(sourceName.c_str(),
|
VARDATA(pieces[i].payload), slen, &compiled);
|
pieces[i].status = "VALID";
|
for (int c = 0; c < ncls; c++)
|
{
|
bool found = false;
|
for (size_t j = 0; j < pieces.size(); j++)
|
{
|
if (pieces[j].kind == "class" && pieces[j].shortName == compiled[c].name)
|
{
|
pieces[j].payload = compiled[c].bytes;
|
pieces[j].status = "VALID";
|
pieces[j].derived = sourceName;
|
found = true;
|
break;
|
}
|
}
|
if (!found)
|
{
|
Piece extra;
|
extra.shortName = compiled[c].name;
|
extra.longName = slashesToDots(extra.shortName);
|
extra.kind = "class";
|
extra.payload = compiled[c].bytes;
|
extra.derived = sourceName;
|
extra.status = "VALID";
|
extras.push_back(extra);
|
}
|
}
|
}
|
for (size_t i = 0; i < extras.size(); i++)
|
pieces.push_back(extras[i]);
|
}
|
for (size_t i = 0; i < pieces.size(); i++)
|
upsert(schema, pieces[i], resolver);
|
}
|
|
static void
|
dropOne(const std::string &schema, const std::string &token)
|
{
|
if (!token.empty() && token[0] == '/')
|
{
|
struct stat st;
|
if (stat(token.c_str(), &st) != 0)
|
return;
|
bytea *payload = readFile(token.c_str());
|
std::vector<Piece> pieces = piecesFromFile(token.c_str(), payload, false);
|
std::vector<std::string> names;
|
for (size_t i = 0; i < pieces.size(); i++)
|
{
|
names.push_back(pieces[i].shortName);
|
names.push_back(pieces[i].longName);
|
}
|
deleteNames(schema, names);
|
return;
|
}
|
std::vector<std::string> names;
|
names.push_back(token);
|
names.push_back(dotsToSlashes(token));
|
deleteNames(schema, names);
|
}
|
|
static void
|
runLoad(const std::string &options, const std::string &resolverArg)
|
{
|
std::string schema = currentSchema();
|
Options opt = parseOptions(options, resolverArg, schema);
|
if (!opt.schema.empty())
|
schema = opt.schema;
|
if (SPI_connect() != SPI_OK_CONNECT)
|
elog(ERROR, "dbms_java: SPI не открыт");
|
for (size_t i = 0; i < opt.files.size(); i++)
|
loadOne(schema, opt.resolver, opt.files[i], opt.resolve);
|
SPI_finish();
|
rudb_java_reset_session();
|
ereport(LOG,
|
(errmsg("dbms_java: загрузка объектов завершена"),
|
errdetail_internal("Output: [Status: OK, Files: %zu]", opt.files.size())));
|
}
|
|
static void
|
runDrop(const std::string &options)
|
{
|
std::string schema = currentSchema();
|
Options opt = parseOptions(options, "", schema);
|
if (SPI_connect() != SPI_OK_CONNECT)
|
elog(ERROR, "dbms_java: SPI не открыт");
|
for (size_t i = 0; i < opt.files.size(); i++)
|
dropOne(schema, opt.files[i]);
|
SPI_finish();
|
rudb_java_reset_session();
|
ereport(LOG,
|
(errmsg("dbms_java: удаление объектов завершено"),
|
errdetail_internal("Output: [Status: OK, Tokens: %zu]", opt.files.size())));
|
}
|
|
static Datum
|
statusTuple(PG_FUNCTION_ARGS)
|
{
|
TupleDesc tupdesc;
|
Datum values[1];
|
bool nulls[1] = {false};
|
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
|
elog(ERROR, "dbms_java: статус loadjava должен быть составным");
|
BlessTupleDesc(tupdesc);
|
values[0] = DirectFunctionCall1(int4_numeric, Int32GetDatum(1));
|
HeapTuple tuple = heap_form_tuple(tupdesc, values, nulls);
|
return HeapTupleGetDatum(tuple);
|
}
|
|
static void
|
storeNamed(const std::string &schema, const std::string &name, const std::string &kind,
|
bytea *payload, const std::string &resolver, const std::string &derived)
|
{
|
if (kind != "source" && kind != "class" && kind != "resource" && kind != "jar")
|
failJava("dbms_java: неизвестный вид объекта");
|
Piece piece;
|
piece.kind = kind;
|
piece.payload = payload;
|
piece.derived = derived;
|
if (name.find('/') != std::string::npos)
|
{
|
piece.shortName = name;
|
piece.longName = slashesToDots(name);
|
}
|
else
|
{
|
piece.longName = name;
|
piece.shortName = dotsToSlashes(name);
|
}
|
if (SPI_connect() != SPI_OK_CONNECT)
|
elog(ERROR, "dbms_java: SPI не открыт");
|
upsert(schema, piece, resolver);
|
if (kind == "source")
|
{
|
Piece cls = piece;
|
cls.kind = "class";
|
cls.payload = NULL;
|
cls.derived = piece.shortName;
|
upsert(schema, cls, resolver);
|
}
|
SPI_finish();
|
}
|
|
static int verifierFlag_ = 1;
|
static int systemLoading_ = 0;
|
|
struct ExecGrant
|
{
|
std::string objectName_;
|
std::string objectSchema_;
|
std::string objectType_;
|
std::string grantee_;
|
int grantFlag_;
|
};
|
|
static std::vector<ExecGrant> execGrants_;
|
|
static void
|
requireVerifier(void)
|
{
|
if (!superuser())
|
ereport(ERROR,
|
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
|
errmsg("dbms_java: нет права Verifier")));
|
}
|
|
static void
|
credRequireUser(const char *dbuser)
|
{
|
if (!OidIsValid(get_role_oid(dbuser, true)))
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
errmsg("ORA-01918: user '%s' does not exist", dbuser)));
|
}
|
|
static void
|
credRequireSuper(void)
|
{
|
if (!superuser())
|
ereport(ERROR,
|
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
|
errmsg("ORA-01031: insufficient privileges")));
|
}
|
|
static void
|
credStore(const char *schema_name, const char *os_user, bool drop)
|
{
|
Oid argtypes[2] = {TEXTOID, TEXTOID};
|
Datum values[2];
|
char nulls[2] = {' ', ' '};
|
int rc;
|
|
values[0] = CStringGetTextDatum(schema_name);
|
SPI_connect();
|
if (drop)
|
rc = SPI_execute_with_args(
|
"DELETE FROM pg_catalog.dbms_java_exec_credentials WHERE schema_name = $1",
|
1, argtypes, values, nulls, false, 0);
|
else
|
{
|
values[1] = CStringGetTextDatum(os_user);
|
rc = SPI_execute_with_args(
|
"UPDATE pg_catalog.dbms_java_exec_credentials SET os_user = $2 "
|
"WHERE schema_name = $1",
|
2, argtypes, values, nulls, false, 0);
|
if (rc == SPI_OK_UPDATE && SPI_processed == 0)
|
rc = SPI_execute_with_args(
|
"INSERT INTO pg_catalog.dbms_java_exec_credentials (schema_name, os_user) "
|
"VALUES ($1, $2)",
|
2, argtypes, values, nulls, false, 0);
|
}
|
SPI_finish();
|
if (rc < 0)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("dbms_java: не записаны учётные данные")));
|
}
|
|
static void
|
rememberExec(const char *objectName, const char *objectSchema, const char *objectType,
|
const char *grantee, int grantFlag)
|
{
|
for (size_t i = 0; i < execGrants_.size(); i++)
|
{
|
ExecGrant &row = execGrants_[i];
|
if (row.objectName_ == objectName && row.objectSchema_ == objectSchema
|
&& row.objectType_ == objectType && row.grantee_ == grantee)
|
{
|
row.grantFlag_ = grantFlag;
|
return;
|
}
|
}
|
ExecGrant row;
|
row.objectName_ = objectName;
|
row.objectSchema_ = objectSchema;
|
row.objectType_ = objectType;
|
row.grantee_ = grantee;
|
row.grantFlag_ = grantFlag;
|
execGrants_.push_back(row);
|
}
|
|
static void
|
missingJar(void)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
errmsg("dbms_java: jar close error status = 6")));
|
}
|
|
static void
|
moduleNpe(void)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("ORA-29532: Java call terminated by uncaught Java exception: java.lang.NullPointerException")));
|
}
|
|
static void
|
moduleMissing(const char *kind, const char *module_name, const char *schema_name)
|
{
|
const char *shown = (module_name == NULL || module_name[0] == '\0') ? "null" : module_name;
|
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("ORA-29532: Java call terminated by uncaught Java exception: java.lang.RuntimeException: Module %s for %s not found in schema %s",
|
kind, shown, schema_name)));
|
}
|
|
static bool
|
moduleSchemaOk(const char *schema_name)
|
{
|
if (schema_name == NULL || schema_name[0] == '\0')
|
return false;
|
return OidIsValid(get_role_oid(schema_name, true));
|
}
|
|
static void
|
ncompOra(const char *detail)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("ORA-29532: Java call terminated by uncaught Java exception: %s", detail)));
|
}
|
|
static void
|
ncompMissingClass(const char *class_name)
|
{
|
char *user = GetUserNameFromId(GetUserId(), false);
|
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("ORA-29532: Java call terminated by uncaught Java exception: java.lang.ClassNotFoundException: %s in <%s>",
|
class_name, user != NULL ? user : "")));
|
}
|
|
static bool
|
loadClassMethods(const char *class_name, std::vector<NcompMeth> *methods)
|
{
|
std::string schema = currentSchema();
|
Oid argtypes[2] = {TEXTOID, TEXTOID};
|
Datum values[2];
|
char nulls[2] = {' ', ' '};
|
Oid saveUser;
|
int saveSec;
|
MemoryContext caller = CurrentMemoryContext;
|
char *image = NULL;
|
int imageLen = 0;
|
volatile bool got = false;
|
|
values[0] = CStringGetTextDatum(schema.c_str());
|
values[1] = CStringGetTextDatum(class_name);
|
GetUserIdAndSecContext(&saveUser, &saveSec);
|
SetUserIdAndSecContext(BOOTSTRAP_SUPERUSERID,
|
saveSec | SECURITY_LOCAL_USERID_CHANGE);
|
PG_TRY();
|
{
|
bool isnull = false;
|
|
if (SPI_connect() != SPI_OK_CONNECT)
|
elog(ERROR, "dbms_java: SPI не открыт");
|
if (SPI_execute_with_args(
|
"SELECT bytes FROM pg_catalog.dbms_java_object "
|
"WHERE schema_name = $1 AND short_name = $2 AND kind = 'class' "
|
"AND bytes IS NOT NULL LIMIT 1",
|
2, argtypes, values, nulls, true, 1) == SPI_OK_SELECT
|
&& SPI_processed == 1)
|
{
|
Datum raw = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
if (!isnull)
|
{
|
bytea *payload = DatumGetByteaPP(raw);
|
imageLen = VARSIZE_ANY_EXHDR(payload);
|
image = (char *) MemoryContextAlloc(caller, imageLen);
|
memcpy(image, VARDATA_ANY(payload), imageLen);
|
got = true;
|
}
|
}
|
SPI_finish();
|
}
|
PG_CATCH();
|
{
|
SetUserIdAndSecContext(saveUser, saveSec);
|
PG_RE_THROW();
|
}
|
PG_END_TRY();
|
SetUserIdAndSecContext(saveUser, saveSec);
|
if (!got)
|
return false;
|
bool parsed = classMethodsFromBytes((const unsigned char *) image, (size_t) imageLen, methods);
|
pfree(image);
|
return parsed;
|
}
|
|
static bool
|
ncompHasName(const std::vector<NcompMeth> &methods, const char *method_name)
|
{
|
for (size_t i = 0; i < methods.size(); i++)
|
{
|
if (methods[i].name == method_name)
|
return true;
|
}
|
return false;
|
}
|
|
static bool
|
ncompHasExact(const std::vector<NcompMeth> &methods, const char *method_name, const char *method_sig)
|
{
|
for (size_t i = 0; i < methods.size(); i++)
|
{
|
if (methods[i].name == method_name && methods[i].desc == method_sig)
|
return true;
|
}
|
return false;
|
}
|
|
static std::string
|
jniParams(const char *desc)
|
{
|
std::string out = "(";
|
bool first = true;
|
size_t pos = 0;
|
std::string text = desc != NULL ? desc : "";
|
|
if (text.empty() || text[0] != '(')
|
return "()";
|
pos = 1;
|
while (pos < text.size() && text[pos] != ')')
|
{
|
std::string type;
|
int dims = 0;
|
|
while (pos < text.size() && text[pos] == '[')
|
{
|
dims++;
|
pos++;
|
}
|
if (pos >= text.size())
|
break;
|
if (text[pos] == 'L')
|
{
|
size_t start = ++pos;
|
while (pos < text.size() && text[pos] != ';')
|
pos++;
|
type = text.substr(start, pos - start);
|
for (size_t k = 0; k < type.size(); k++)
|
{
|
if (type[k] == '/')
|
type[k] = '.';
|
}
|
if (pos < text.size() && text[pos] == ';')
|
pos++;
|
}
|
else
|
{
|
switch (text[pos])
|
{
|
case 'B': type = "byte"; break;
|
case 'C': type = "char"; break;
|
case 'D': type = "double"; break;
|
case 'F': type = "float"; break;
|
case 'I': type = "int"; break;
|
case 'J': type = "long"; break;
|
case 'S': type = "short"; break;
|
case 'Z': type = "boolean"; break;
|
case 'V': type = "void"; break;
|
default: type = "?"; break;
|
}
|
pos++;
|
}
|
while (dims-- > 0)
|
type += "[]";
|
if (!first)
|
out += ",";
|
first = false;
|
out += type;
|
}
|
out += ")";
|
return out;
|
}
|
|
static void
|
ncompNoMethod(const char *class_name, const char *method_name, const char *params)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("ORA-29532: Java call terminated by uncaught Java exception: java.lang.NoSuchMethodException: %s.%s%s",
|
class_name, method_name, params)));
|
}
|
|
static Datum
|
ncompCount(const char *class_name)
|
{
|
std::vector<NcompMeth> methods;
|
|
if (!loadClassMethods(class_name, &methods))
|
ncompMissingClass(class_name);
|
return DirectFunctionCall1(int4_numeric, Int32GetDatum((int32) methods.size()));
|
}
|
|
} // namespace DbmsJava
|
|
extern "C"
|
{
|
|
PG_FUNCTION_INFO_V1(dbms_java_loadjava);
|
PG_FUNCTION_INFO_V1(dbms_java_loadjava_resolver);
|
PG_FUNCTION_INFO_V1(dbms_java_loadjava_status);
|
PG_FUNCTION_INFO_V1(dbms_java_dropjava);
|
PG_FUNCTION_INFO_V1(dbms_java_loadjava_bytes);
|
PG_FUNCTION_INFO_V1(dbms_java_create_source);
|
PG_FUNCTION_INFO_V1(dbms_java_longname);
|
PG_FUNCTION_INFO_V1(dbms_java_shortname);
|
PG_FUNCTION_INFO_V1(dbms_java_sharedprivateclassname);
|
PG_FUNCTION_INFO_V1(dbms_java_resolver);
|
PG_FUNCTION_INFO_V1(dbms_java_derivedfrom);
|
PG_FUNCTION_INFO_V1(dbms_java_fixed_in_instance);
|
PG_FUNCTION_INFO_V1(dbms_java_set_fixed_in_instance);
|
PG_FUNCTION_INFO_V1(dbms_java_export_source);
|
PG_FUNCTION_INFO_V1(dbms_java_export_source_name);
|
PG_FUNCTION_INFO_V1(dbms_java_export_source_clob);
|
PG_FUNCTION_INFO_V1(dbms_java_export_source_clob_schema);
|
PG_FUNCTION_INFO_V1(dbms_java_export_class);
|
PG_FUNCTION_INFO_V1(dbms_java_export_class_schema);
|
PG_FUNCTION_INFO_V1(dbms_java_export_resource);
|
PG_FUNCTION_INFO_V1(dbms_java_export_resource_schema);
|
PG_FUNCTION_INFO_V1(dbms_java_export_resource_clob);
|
PG_FUNCTION_INFO_V1(dbms_java_export_resource_clob_schema);
|
PG_FUNCTION_INFO_V1(dbms_java_grant_permission);
|
PG_FUNCTION_INFO_V1(dbms_java_grant_permission_key);
|
PG_FUNCTION_INFO_V1(dbms_java_restrict_permission);
|
PG_FUNCTION_INFO_V1(dbms_java_restrict_permission_key);
|
PG_FUNCTION_INFO_V1(dbms_java_grant_policy_permission);
|
PG_FUNCTION_INFO_V1(dbms_java_grant_policy_permission_key);
|
PG_FUNCTION_INFO_V1(dbms_java_revoke_permission);
|
PG_FUNCTION_INFO_V1(dbms_java_disable_permission);
|
PG_FUNCTION_INFO_V1(dbms_java_enable_permission);
|
PG_FUNCTION_INFO_V1(dbms_java_delete_permission);
|
PG_FUNCTION_INFO_V1(dbms_java_set_permission_debug);
|
PG_FUNCTION_INFO_V1(dbms_java_get_compiler_option);
|
PG_FUNCTION_INFO_V1(dbms_java_set_compiler_option);
|
PG_FUNCTION_INFO_V1(dbms_java_reset_compiler_option);
|
PG_FUNCTION_INFO_V1(dbms_java_set_native_compiler_option);
|
PG_FUNCTION_INFO_V1(dbms_java_unset_native_compiler_option);
|
PG_FUNCTION_INFO_V1(dbms_java_native_compiler_options);
|
PG_FUNCTION_INFO_V1(dbms_java_decode_native_compiler_option);
|
PG_FUNCTION_INFO_V1(dbms_java_set_property);
|
PG_FUNCTION_INFO_V1(dbms_java_get_property);
|
PG_FUNCTION_INFO_V1(dbms_java_remove_property);
|
PG_FUNCTION_INFO_V1(dbms_java_show_property);
|
PG_FUNCTION_INFO_V1(dbms_java_set_preference);
|
PG_FUNCTION_INFO_V1(dbms_java_jar_digest);
|
PG_FUNCTION_INFO_V1(dbms_java_jar_digest_bytes);
|
PG_FUNCTION_INFO_V1(dbms_java_set_verifier);
|
PG_FUNCTION_INFO_V1(dbms_java_set_runtime_exec_credentials);
|
PG_FUNCTION_INFO_V1(dbms_java_jar_name_from_module);
|
PG_FUNCTION_INFO_V1(dbms_java_hotload_module);
|
PG_FUNCTION_INFO_V1(dbms_java_unhotload_module);
|
PG_FUNCTION_INFO_V1(dbms_java_compile_class);
|
PG_FUNCTION_INFO_V1(dbms_java_compile_method);
|
PG_FUNCTION_INFO_V1(dbms_java_uncompile_class);
|
PG_FUNCTION_INFO_V1(dbms_java_uncompile_method);
|
PG_FUNCTION_INFO_V1(dbms_java_dump_native_machine_code);
|
PG_FUNCTION_INFO_V1(dbms_java_start_jmx_agent);
|
PG_FUNCTION_INFO_V1(dbms_java_set_system_class_loading);
|
PG_FUNCTION_INFO_V1(dbms_java_set_execute_privilege);
|
PG_FUNCTION_INFO_V1(dbms_java_endsession);
|
PG_FUNCTION_INFO_V1(dbms_java_endsession_and_related_state);
|
PG_FUNCTION_INFO_V1(dbms_java_runjava);
|
PG_FUNCTION_INFO_V1(dbms_java_runjava_in_current_session);
|
PG_FUNCTION_INFO_V1(dbms_java_set_output_to_sql);
|
PG_FUNCTION_INFO_V1(dbms_java_remove_output_to_sql);
|
PG_FUNCTION_INFO_V1(dbms_java_enable_output_to_sql);
|
PG_FUNCTION_INFO_V1(dbms_java_disable_output_to_sql);
|
PG_FUNCTION_INFO_V1(dbms_java_query_output_to_sql);
|
PG_FUNCTION_INFO_V1(dbms_java_set_output_to_java);
|
PG_FUNCTION_INFO_V1(dbms_java_remove_output_to_java);
|
PG_FUNCTION_INFO_V1(dbms_java_enable_output_to_java);
|
PG_FUNCTION_INFO_V1(dbms_java_disable_output_to_java);
|
PG_FUNCTION_INFO_V1(dbms_java_query_output_to_java);
|
PG_FUNCTION_INFO_V1(dbms_java_set_output_to_file);
|
PG_FUNCTION_INFO_V1(dbms_java_remove_output_to_file);
|
PG_FUNCTION_INFO_V1(dbms_java_enable_output_to_file);
|
PG_FUNCTION_INFO_V1(dbms_java_disable_output_to_file);
|
PG_FUNCTION_INFO_V1(dbms_java_query_output_to_file);
|
PG_FUNCTION_INFO_V1(dbms_java_initialize_output_to_file);
|
PG_FUNCTION_INFO_V1(dbms_java_finalize_output_to_file);
|
PG_FUNCTION_INFO_V1(dbms_java_enable_output_to_trc);
|
PG_FUNCTION_INFO_V1(dbms_java_disable_output_to_trc);
|
PG_FUNCTION_INFO_V1(dbms_java_query_output_to_trc);
|
|
Datum
|
dbms_java_loadjava(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0))
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("dbms_java: опции не заданы")));
|
DbmsJava::runLoad(DbmsJava::textOrEmpty(PG_GETARG_DATUM(0), false), "");
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_loadjava_resolver(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0))
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("dbms_java: опции не заданы")));
|
std::string resolver = PG_ARGISNULL(1) ? std::string() : DbmsJava::textOrEmpty(PG_GETARG_DATUM(1), false);
|
DbmsJava::runLoad(DbmsJava::textOrEmpty(PG_GETARG_DATUM(0), false), resolver);
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_loadjava_status(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0))
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("dbms_java: опции не заданы")));
|
std::string resolver = PG_ARGISNULL(1) ? std::string() : DbmsJava::textOrEmpty(PG_GETARG_DATUM(1), false);
|
DbmsJava::runLoad(DbmsJava::textOrEmpty(PG_GETARG_DATUM(0), false), resolver);
|
PG_RETURN_DATUM(DbmsJava::statusTuple(fcinfo));
|
}
|
|
Datum
|
dbms_java_dropjava(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0))
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("dbms_java: опции не заданы")));
|
DbmsJava::runDrop(DbmsJava::textOrEmpty(PG_GETARG_DATUM(0), false));
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_loadjava_bytes(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("dbms_java: имя или вид не заданы")));
|
std::string schema = PG_ARGISNULL(0) ? DbmsJava::currentSchema()
|
: DbmsJava::textOrEmpty(PG_GETARG_DATUM(0), false);
|
std::string name = DbmsJava::textOrEmpty(PG_GETARG_DATUM(1), false);
|
std::string kind = DbmsJava::textOrEmpty(PG_GETARG_DATUM(2), false);
|
bytea *payload = PG_ARGISNULL(3) ? NULL : PG_GETARG_BYTEA_P(3);
|
std::string resolver = PG_ARGISNULL(4) ? DbmsJava::defaultResolver(schema)
|
: DbmsJava::textOrEmpty(PG_GETARG_DATUM(4), false);
|
DbmsJava::storeNamed(schema, name, kind, payload, resolver, "");
|
PG_RETURN_VOID();
|
}
|
|
static bool
|
blankSource(const std::string &source)
|
{
|
for (size_t i = 0; i < source.size(); i++)
|
{
|
if (!isspace((unsigned char) source[i]))
|
return false;
|
}
|
return true;
|
}
|
|
static void
|
deleteDerived(const std::string &schema, const std::string &shortName)
|
{
|
Oid argtypes[2] = {TEXTOID, TEXTOID};
|
Datum values[2];
|
char nulls[2] = {' ', ' '};
|
values[0] = CStringGetTextDatum(schema.c_str());
|
values[1] = CStringGetTextDatum(shortName.c_str());
|
SPI_execute_with_args(
|
"DELETE FROM pg_catalog.dbms_java_object "
|
"WHERE schema_name = $1 AND (short_name = $2 OR derived_from = $2)",
|
2, argtypes, values, nulls, false, 0);
|
}
|
|
Datum
|
dbms_java_create_source(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("dbms_java: имя или исходник не заданы")));
|
std::string name = DbmsJava::textOrEmpty(PG_GETARG_DATUM(0), false);
|
std::string source = DbmsJava::textOrEmpty(PG_GETARG_DATUM(1), false);
|
std::string schema = PG_ARGISNULL(2) ? DbmsJava::currentSchema()
|
: DbmsJava::textOrEmpty(PG_GETARG_DATUM(2), false);
|
bool resolve = PG_ARGISNULL(3) ? true : PG_GETARG_BOOL(3);
|
std::string resolver = DbmsJava::defaultResolver(schema);
|
bool blank = blankSource(source);
|
DbmsJavaCompiled *compiled = NULL;
|
int ncls = 0;
|
|
if (resolve && !blank)
|
ncls = rudb_java_compile_classes(DbmsJava::dotsToSlashes(name).c_str(),
|
source.data(), (int) source.size(), &compiled);
|
if (SPI_connect() != SPI_OK_CONNECT)
|
elog(ERROR, "dbms_java: SPI не открыт");
|
DbmsJava::Piece piece;
|
if (name.find('/') != std::string::npos)
|
{
|
piece.shortName = name;
|
piece.longName = DbmsJava::slashesToDots(name);
|
}
|
else
|
{
|
piece.longName = name;
|
piece.shortName = DbmsJava::dotsToSlashes(name);
|
}
|
if (resolve)
|
deleteDerived(schema, piece.shortName);
|
piece.kind = "source";
|
piece.payload = DbmsJava::copyBytes(source.data(), source.size());
|
piece.status = (resolve || blank) ? "VALID" : "INVALID";
|
DbmsJava::upsert(schema, piece, resolver);
|
if (resolve && !blank)
|
{
|
for (int i = 0; i < ncls; i++)
|
{
|
DbmsJava::Piece cls;
|
cls.shortName = compiled[i].name;
|
cls.longName = DbmsJava::slashesToDots(cls.shortName);
|
cls.kind = "class";
|
cls.payload = compiled[i].bytes;
|
cls.derived = piece.shortName;
|
cls.status = "VALID";
|
DbmsJava::upsert(schema, cls, resolver);
|
}
|
}
|
else if (!resolve)
|
{
|
DbmsJava::Piece cls = piece;
|
cls.kind = "class";
|
cls.payload = NULL;
|
cls.derived = piece.shortName;
|
cls.status = "INVALID";
|
DbmsJava::upsert(schema, cls, resolver);
|
}
|
SPI_finish();
|
PG_RETURN_VOID();
|
}
|
|
static Datum
|
nameEcho(PG_FUNCTION_ARGS, bool shorten)
|
{
|
text *in;
|
int len;
|
|
if (PG_ARGISNULL(0))
|
PG_RETURN_NULL();
|
in = PG_GETARG_TEXT_PP(0);
|
len = VARSIZE_ANY_EXHDR(in);
|
if (len == 0 || (shorten && len > 128))
|
PG_RETURN_NULL();
|
PG_RETURN_TEXT_P(in);
|
}
|
|
Datum
|
dbms_java_longname(PG_FUNCTION_ARGS)
|
{
|
return nameEcho(fcinfo, false);
|
}
|
|
Datum
|
dbms_java_shortname(PG_FUNCTION_ARGS)
|
{
|
return nameEcho(fcinfo, true);
|
}
|
|
Datum
|
dbms_java_sharedprivateclassname(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
PG_RETURN_NULL();
|
}
|
|
static bool
|
lookupAttr(const char *name, const char *owner, const char *typeName, const char *column, std::string *out)
|
{
|
std::string kind = typeName;
|
for (size_t i = 0; i < kind.size(); i++)
|
kind[i] = (char) tolower((unsigned char) kind[i]);
|
Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID};
|
Datum values[3];
|
char nulls[3] = {' ', ' ', ' '};
|
std::string sql = std::string("SELECT ") + column +
|
" FROM pg_catalog.dbms_java_object "
|
"WHERE lower(schema_name) = lower($2) "
|
"AND (short_name = $1 OR long_name = $1) AND kind = $3 LIMIT 1";
|
bool isnull = false;
|
bool found = false;
|
|
values[0] = CStringGetTextDatum(name);
|
values[1] = CStringGetTextDatum(owner);
|
values[2] = CStringGetTextDatum(kind.c_str());
|
SPI_connect();
|
int rc = SPI_execute_with_args(sql.c_str(), 3, argtypes, values, nulls, true, 1);
|
if (rc == SPI_OK_SELECT && SPI_processed == 1)
|
{
|
Datum d = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
if (!isnull)
|
{
|
if (strcmp(column, "fixed_in_instance") == 0)
|
*out = DatumGetBool(d) ? "1" : "0";
|
else
|
*out = TextDatumGetCString(d);
|
found = true;
|
}
|
else
|
found = true;
|
}
|
SPI_finish();
|
return found && !isnull;
|
}
|
|
Datum
|
dbms_java_resolver(PG_FUNCTION_ARGS)
|
{
|
std::string value;
|
if (PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2))
|
PG_RETURN_NULL();
|
if (!lookupAttr(text_to_cstring(PG_GETARG_TEXT_PP(0)),
|
text_to_cstring(PG_GETARG_TEXT_PP(1)),
|
text_to_cstring(PG_GETARG_TEXT_PP(2)),
|
"resolver", &value))
|
PG_RETURN_NULL();
|
PG_RETURN_TEXT_P(cstring_to_text(value.c_str()));
|
}
|
|
Datum
|
dbms_java_derivedfrom(PG_FUNCTION_ARGS)
|
{
|
std::string value;
|
if (PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2))
|
PG_RETURN_NULL();
|
if (!lookupAttr(text_to_cstring(PG_GETARG_TEXT_PP(0)),
|
text_to_cstring(PG_GETARG_TEXT_PP(1)),
|
text_to_cstring(PG_GETARG_TEXT_PP(2)),
|
"derived_from", &value))
|
PG_RETURN_NULL();
|
PG_RETURN_TEXT_P(cstring_to_text(value.c_str()));
|
}
|
|
Datum
|
dbms_java_fixed_in_instance(PG_FUNCTION_ARGS)
|
{
|
std::string value;
|
if (PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2))
|
PG_RETURN_NULL();
|
if (!lookupAttr(text_to_cstring(PG_GETARG_TEXT_PP(0)),
|
text_to_cstring(PG_GETARG_TEXT_PP(1)),
|
text_to_cstring(PG_GETARG_TEXT_PP(2)),
|
"fixed_in_instance", &value))
|
PG_RETURN_NULL();
|
PG_RETURN_DATUM(DirectFunctionCall1(int4_numeric, Int32GetDatum(value == "1" ? 1 : 0)));
|
}
|
|
Datum
|
dbms_java_set_fixed_in_instance(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
PG_RETURN_VOID();
|
}
|
|
static std::string
|
exportSchema()
|
{
|
List *path = fetch_search_path(false);
|
Oid nsp = linitial_oid(path);
|
list_free(path);
|
char *name = get_namespace_name(nsp);
|
std::string out(name != NULL ? name : "public");
|
if (name != NULL)
|
pfree(name);
|
return out;
|
}
|
|
static bytea *
|
exportBytes(const char *name, const char *schema, const char *kind)
|
{
|
Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID};
|
Datum values[3];
|
char nulls[3] = {' ', ' ', ' '};
|
const char *sql =
|
"SELECT bytes FROM pg_catalog.dbms_java_object "
|
"WHERE lower(schema_name) = lower($2) "
|
"AND (short_name = $1 OR long_name = $1) AND kind = $3 LIMIT 1";
|
bool isnull = true;
|
bytea *copy = NULL;
|
MemoryContext caller = CurrentMemoryContext;
|
|
values[0] = CStringGetTextDatum(name);
|
values[1] = CStringGetTextDatum(schema);
|
values[2] = CStringGetTextDatum(kind);
|
SPI_connect();
|
int rc = SPI_execute_with_args(sql, 3, argtypes, values, nulls, true, 1);
|
if (rc == SPI_OK_SELECT && SPI_processed == 1)
|
{
|
Datum d = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
if (!isnull)
|
{
|
bytea *src = DatumGetByteaPP(d);
|
Size sz = VARSIZE_ANY(src);
|
MemoryContextSwitchTo(caller);
|
copy = (bytea *) palloc(sz);
|
memcpy(copy, src, sz);
|
}
|
}
|
SPI_finish();
|
if (copy == NULL)
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
errmsg("dbms_java: объект не найден")));
|
return copy;
|
}
|
|
static Datum
|
exportOut(PG_FUNCTION_ARGS, const char *kind, bool withSchema, bool asText)
|
{
|
char *name;
|
std::string schema;
|
bytea *payload;
|
TupleDesc tupdesc;
|
Datum values[1];
|
bool nulls[1] = {false};
|
|
if (PG_ARGISNULL(0))
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
errmsg("dbms_java: объект не найден")));
|
name = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
schema = exportSchema();
|
if (withSchema && !PG_ARGISNULL(1))
|
schema = text_to_cstring(PG_GETARG_TEXT_PP(1));
|
payload = exportBytes(name, schema.c_str(), kind);
|
tupdesc = CreateTemplateTupleDesc(1);
|
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "src",
|
asText ? TEXTOID : BYTEAOID, -1, 0);
|
TupleDescFinalize(tupdesc);
|
BlessTupleDesc(tupdesc);
|
if (asText)
|
{
|
bytea *raw = pg_detoast_datum_packed(payload);
|
values[0] = PointerGetDatum(cstring_to_text_with_len(VARDATA_ANY(raw),
|
VARSIZE_ANY_EXHDR(raw)));
|
}
|
else
|
values[0] = PointerGetDatum(payload);
|
PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
|
}
|
|
Datum
|
dbms_java_export_source(PG_FUNCTION_ARGS)
|
{
|
return exportOut(fcinfo, "source", true, false);
|
}
|
|
Datum
|
dbms_java_export_source_name(PG_FUNCTION_ARGS)
|
{
|
return exportOut(fcinfo, "source", false, false);
|
}
|
|
Datum
|
dbms_java_export_source_clob(PG_FUNCTION_ARGS)
|
{
|
return exportOut(fcinfo, "source", false, true);
|
}
|
|
Datum
|
dbms_java_export_source_clob_schema(PG_FUNCTION_ARGS)
|
{
|
return exportOut(fcinfo, "source", true, true);
|
}
|
|
Datum
|
dbms_java_export_class(PG_FUNCTION_ARGS)
|
{
|
return exportOut(fcinfo, "class", false, false);
|
}
|
|
Datum
|
dbms_java_export_class_schema(PG_FUNCTION_ARGS)
|
{
|
return exportOut(fcinfo, "class", true, false);
|
}
|
|
Datum
|
dbms_java_export_resource(PG_FUNCTION_ARGS)
|
{
|
return exportOut(fcinfo, "resource", false, false);
|
}
|
|
Datum
|
dbms_java_export_resource_schema(PG_FUNCTION_ARGS)
|
{
|
return exportOut(fcinfo, "resource", true, false);
|
}
|
|
Datum
|
dbms_java_export_resource_clob(PG_FUNCTION_ARGS)
|
{
|
return exportOut(fcinfo, "resource", false, true);
|
}
|
|
Datum
|
dbms_java_export_resource_clob_schema(PG_FUNCTION_ARGS)
|
{
|
return exportOut(fcinfo, "resource", true, true);
|
}
|
|
static int64
|
policyInsert(const char *grantee, const char *permType, const char *permName,
|
const char *permAction, bool actionNull, const char *kind)
|
{
|
Oid argtypes[5] = {TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID};
|
Datum values[5];
|
char nulls[5] = {' ', ' ', ' ', ' ', ' '};
|
const char *sql =
|
"INSERT INTO pg_catalog.dbms_java_policy "
|
"(key, grantee, perm_type, perm_name, perm_action, kind, enabled) "
|
"OVERRIDING SYSTEM VALUE "
|
"SELECT COALESCE(MAX(key), 0) + 1, $1, $2, $3, $4, $5, true "
|
"FROM pg_catalog.dbms_java_policy RETURNING key";
|
MemoryContext caller = CurrentMemoryContext;
|
int64 key = 0;
|
bool isnull = true;
|
|
values[0] = CStringGetTextDatum(grantee);
|
values[1] = CStringGetTextDatum(permType);
|
values[2] = CStringGetTextDatum(permName);
|
values[3] = actionNull ? (Datum) 0 : CStringGetTextDatum(permAction);
|
values[4] = CStringGetTextDatum(kind);
|
if (actionNull)
|
nulls[3] = 'n';
|
SPI_connect();
|
int rc = SPI_execute_with_args(sql, 5, argtypes, values, nulls, false, 1);
|
if (rc == SPI_OK_INSERT_RETURNING && SPI_processed == 1)
|
{
|
Datum d = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
if (!isnull)
|
key = DatumGetInt64(d);
|
}
|
SPI_finish();
|
(void) caller;
|
if (isnull)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("dbms_java: строка политики не записана")));
|
return key;
|
}
|
|
static bool
|
policyEnableMatch(const char *grantee, const char *permType, const char *permName,
|
const char *permAction, bool actionNull, const char *kind)
|
{
|
Oid argtypes[5] = {TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID};
|
Datum values[5];
|
char nulls[5] = {' ', ' ', ' ', ' ', ' '};
|
const char *sql =
|
"UPDATE pg_catalog.dbms_java_policy SET enabled = true "
|
"WHERE grantee = $1 AND perm_type = $2 AND perm_name = $3 "
|
"AND perm_action IS NOT DISTINCT FROM $4 AND kind = $5";
|
|
values[0] = CStringGetTextDatum(grantee);
|
values[1] = CStringGetTextDatum(permType);
|
values[2] = CStringGetTextDatum(permName);
|
values[3] = actionNull ? (Datum) 0 : CStringGetTextDatum(permAction);
|
values[4] = CStringGetTextDatum(kind);
|
if (actionNull)
|
nulls[3] = 'n';
|
SPI_connect();
|
SPI_execute_with_args(sql, 5, argtypes, values, nulls, false, 0);
|
bool hit = SPI_processed > 0;
|
SPI_finish();
|
return hit;
|
}
|
|
static Datum
|
policyKeyTuple(PG_FUNCTION_ARGS, int64 key)
|
{
|
TupleDesc tupdesc = CreateTemplateTupleDesc(1);
|
Datum values[1];
|
bool nulls[1] = {false};
|
|
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "key", NUMERICOID, -1, 0);
|
TupleDescFinalize(tupdesc);
|
BlessTupleDesc(tupdesc);
|
values[0] = DirectFunctionCall1(int8_numeric, Int64GetDatum(key));
|
PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
|
}
|
|
static void
|
policyGrant(PG_FUNCTION_ARGS, const char *kind, bool alwaysInsert, int64 *keyOut)
|
{
|
char *grantee;
|
char *permType;
|
char *permName;
|
char *permAction = NULL;
|
bool actionNull;
|
|
if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
|
ereport(ERROR,
|
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
|
errmsg("dbms_java: grantee и тип права обязательны")));
|
grantee = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
permType = text_to_cstring(PG_GETARG_TEXT_PP(1));
|
permName = PG_ARGISNULL(2) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(2));
|
actionNull = PG_ARGISNULL(3);
|
if (!actionNull)
|
permAction = text_to_cstring(PG_GETARG_TEXT_PP(3));
|
if (!alwaysInsert &&
|
policyEnableMatch(grantee, permType, permName, permAction, actionNull, kind))
|
{
|
if (keyOut != NULL)
|
*keyOut = -1;
|
return;
|
}
|
int64 key = policyInsert(grantee, permType, permName, permAction, actionNull, kind);
|
if (keyOut != NULL)
|
*keyOut = key;
|
}
|
|
Datum
|
dbms_java_grant_permission(PG_FUNCTION_ARGS)
|
{
|
policyGrant(fcinfo, "GRANT", false, NULL);
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_grant_permission_key(PG_FUNCTION_ARGS)
|
{
|
int64 key = -1;
|
policyGrant(fcinfo, "GRANT", true, &key);
|
return policyKeyTuple(fcinfo, key);
|
}
|
|
Datum
|
dbms_java_restrict_permission(PG_FUNCTION_ARGS)
|
{
|
policyGrant(fcinfo, "RESTRICT", false, NULL);
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_restrict_permission_key(PG_FUNCTION_ARGS)
|
{
|
int64 key = -1;
|
policyGrant(fcinfo, "RESTRICT", true, &key);
|
return policyKeyTuple(fcinfo, key);
|
}
|
|
Datum
|
dbms_java_grant_policy_permission(PG_FUNCTION_ARGS)
|
{
|
char *grantee;
|
char *schema;
|
char *permType;
|
char *permName;
|
std::string storedType = "SYS:oracle.aurora.rdbms.security.PolicyTablePermission";
|
std::string storedName;
|
|
if (PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2))
|
ereport(ERROR,
|
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
|
errmsg("dbms_java: аргументы grant_policy_permission обязательны")));
|
grantee = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
schema = text_to_cstring(PG_GETARG_TEXT_PP(1));
|
permType = text_to_cstring(PG_GETARG_TEXT_PP(2));
|
permName = PG_ARGISNULL(3) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(3));
|
storedName = std::string(schema) + ":" + permType + "#" + permName;
|
if (!policyEnableMatch(grantee, storedType.c_str(), storedName.c_str(), NULL, true, "GRANT"))
|
policyInsert(grantee, storedType.c_str(), storedName.c_str(), NULL, true, "GRANT");
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_grant_policy_permission_key(PG_FUNCTION_ARGS)
|
{
|
char *grantee;
|
char *schema;
|
char *permType;
|
char *permName;
|
std::string storedType = "SYS:oracle.aurora.rdbms.security.PolicyTablePermission";
|
std::string storedName;
|
int64 key;
|
|
if (PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2))
|
ereport(ERROR,
|
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
|
errmsg("dbms_java: аргументы grant_policy_permission обязательны")));
|
grantee = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
schema = text_to_cstring(PG_GETARG_TEXT_PP(1));
|
permType = text_to_cstring(PG_GETARG_TEXT_PP(2));
|
permName = PG_ARGISNULL(3) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(3));
|
storedName = std::string(schema) + ":" + permType + "#" + permName;
|
key = policyInsert(grantee, storedType.c_str(), storedName.c_str(), NULL, true, "GRANT");
|
return policyKeyTuple(fcinfo, key);
|
}
|
|
Datum
|
dbms_java_revoke_permission(PG_FUNCTION_ARGS)
|
{
|
Oid argtypes[4] = {TEXTOID, TEXTOID, TEXTOID, TEXTOID};
|
Datum values[4];
|
char nulls[4] = {' ', ' ', ' ', ' '};
|
const char *sql =
|
"UPDATE pg_catalog.dbms_java_policy SET enabled = false "
|
"WHERE grantee = $1 AND perm_type = $2 AND perm_name = $3 "
|
"AND perm_action IS NOT DISTINCT FROM $4 AND enabled";
|
|
if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
|
PG_RETURN_VOID();
|
values[0] = PG_GETARG_DATUM(0);
|
values[1] = PG_GETARG_DATUM(1);
|
values[2] = PG_ARGISNULL(2) ? CStringGetTextDatum("") : PG_GETARG_DATUM(2);
|
values[3] = PG_ARGISNULL(3) ? (Datum) 0 : PG_GETARG_DATUM(3);
|
if (PG_ARGISNULL(3))
|
nulls[3] = 'n';
|
SPI_connect();
|
SPI_execute_with_args(sql, 4, argtypes, values, nulls, false, 0);
|
SPI_finish();
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_disable_permission(PG_FUNCTION_ARGS)
|
{
|
Oid argtypes[1] = {INT8OID};
|
Datum values[1];
|
char nulls[1] = {' '};
|
const char *sql = "UPDATE pg_catalog.dbms_java_policy SET enabled = false WHERE key = $1";
|
int64 key;
|
|
if (PG_ARGISNULL(0))
|
PG_RETURN_VOID();
|
key = DatumGetInt64(DirectFunctionCall1(numeric_int8, PG_GETARG_DATUM(0)));
|
values[0] = Int64GetDatum(key);
|
SPI_connect();
|
SPI_execute_with_args(sql, 1, argtypes, values, nulls, false, 0);
|
SPI_finish();
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_enable_permission(PG_FUNCTION_ARGS)
|
{
|
Oid argtypes[1] = {INT8OID};
|
Datum values[1];
|
char nulls[1] = {' '};
|
const char *sql = "UPDATE pg_catalog.dbms_java_policy SET enabled = true WHERE key = $1";
|
int64 key;
|
|
if (PG_ARGISNULL(0))
|
PG_RETURN_VOID();
|
key = DatumGetInt64(DirectFunctionCall1(numeric_int8, PG_GETARG_DATUM(0)));
|
values[0] = Int64GetDatum(key);
|
SPI_connect();
|
SPI_execute_with_args(sql, 1, argtypes, values, nulls, false, 0);
|
SPI_finish();
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_delete_permission(PG_FUNCTION_ARGS)
|
{
|
Oid argtypes[1] = {INT8OID};
|
Datum values[1];
|
char nulls[1] = {' '};
|
const char *sql =
|
"DELETE FROM pg_catalog.dbms_java_policy WHERE key = $1 AND NOT enabled";
|
int64 key;
|
|
if (PG_ARGISNULL(0))
|
PG_RETURN_VOID();
|
key = DatumGetInt64(DirectFunctionCall1(numeric_int8, PG_GETARG_DATUM(0)));
|
values[0] = Int64GetDatum(key);
|
SPI_connect();
|
SPI_execute_with_args(sql, 1, argtypes, values, nulls, false, 0);
|
SPI_finish();
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_set_permission_debug(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
PG_RETURN_VOID();
|
}
|
|
static bool
|
compilerFetch(const char *what, const char *optionName, std::string *value)
|
{
|
Oid argtypes[2] = {TEXTOID, TEXTOID};
|
Datum values[2];
|
char nulls[2] = {' ', ' '};
|
const char *sql =
|
"SELECT value FROM pg_catalog.dbms_java_compiler_option "
|
"WHERE schema_name = $1 AND name = $2";
|
MemoryContext caller = CurrentMemoryContext;
|
bool found = false;
|
bool isnull = true;
|
|
values[0] = CStringGetTextDatum(what);
|
values[1] = CStringGetTextDatum(optionName);
|
SPI_connect();
|
int rc = SPI_execute_with_args(sql, 2, argtypes, values, nulls, true, 1);
|
if (rc == SPI_OK_SELECT && SPI_processed == 1)
|
{
|
Datum d = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
if (!isnull)
|
{
|
char *raw = TextDatumGetCString(d);
|
MemoryContextSwitchTo(caller);
|
*value = raw;
|
pfree(raw);
|
found = true;
|
}
|
}
|
SPI_finish();
|
return found;
|
}
|
|
static void
|
compilerStore(const char *what, const char *optionName, const char *value)
|
{
|
Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID};
|
Datum values[3];
|
char nulls[3] = {' ', ' ', ' '};
|
const char *del =
|
"DELETE FROM pg_catalog.dbms_java_compiler_option "
|
"WHERE schema_name = $1 AND name = $2";
|
const char *ins =
|
"INSERT INTO pg_catalog.dbms_java_compiler_option (schema_name, name, value) "
|
"VALUES ($1, $2, $3)";
|
|
values[0] = CStringGetTextDatum(what);
|
values[1] = CStringGetTextDatum(optionName);
|
values[2] = CStringGetTextDatum(value);
|
SPI_connect();
|
SPI_execute_with_args(del, 2, argtypes, values, nulls, false, 0);
|
SPI_execute_with_args(ins, 3, argtypes, values, nulls, false, 0);
|
SPI_finish();
|
}
|
|
static void
|
compilerClear(const char *what, const char *optionName)
|
{
|
Oid argtypes[2] = {TEXTOID, TEXTOID};
|
Datum values[2];
|
char nulls[2] = {' ', ' '};
|
const char *sql =
|
"DELETE FROM pg_catalog.dbms_java_compiler_option "
|
"WHERE schema_name = $1 AND name = $2";
|
|
values[0] = CStringGetTextDatum(what);
|
values[1] = CStringGetTextDatum(optionName);
|
SPI_connect();
|
SPI_execute_with_args(sql, 2, argtypes, values, nulls, false, 0);
|
SPI_finish();
|
}
|
|
Datum
|
dbms_java_get_compiler_option(PG_FUNCTION_ARGS)
|
{
|
std::string value;
|
char *what;
|
char *optionName;
|
|
if (PG_ARGISNULL(1))
|
PG_RETURN_NULL();
|
what = PG_ARGISNULL(0) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(0));
|
optionName = text_to_cstring(PG_GETARG_TEXT_PP(1));
|
if (!compilerFetch(what, optionName, &value))
|
{
|
if (strcmp(optionName, "encoding") == 0)
|
PG_RETURN_TEXT_P(cstring_to_text("UTF-8"));
|
PG_RETURN_NULL();
|
}
|
PG_RETURN_TEXT_P(cstring_to_text(value.c_str()));
|
}
|
|
Datum
|
dbms_java_set_compiler_option(PG_FUNCTION_ARGS)
|
{
|
char *what;
|
char *optionName;
|
char *value;
|
|
if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
|
PG_RETURN_VOID();
|
what = PG_ARGISNULL(0) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(0));
|
optionName = text_to_cstring(PG_GETARG_TEXT_PP(1));
|
value = text_to_cstring(PG_GETARG_TEXT_PP(2));
|
compilerStore(what, optionName, value);
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_reset_compiler_option(PG_FUNCTION_ARGS)
|
{
|
char *what;
|
char *optionName;
|
|
if (PG_ARGISNULL(1))
|
PG_RETURN_VOID();
|
what = PG_ARGISNULL(0) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(0));
|
optionName = text_to_cstring(PG_GETARG_TEXT_PP(1));
|
compilerClear(what, optionName);
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_set_native_compiler_option(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_unset_native_compiler_option(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_native_compiler_options(PG_FUNCTION_ARGS)
|
{
|
FuncCallContext *funcctx;
|
|
if (SRF_IS_FIRSTCALL())
|
funcctx = SRF_FIRSTCALL_INIT();
|
funcctx = SRF_PERCALL_SETUP();
|
SRF_RETURN_DONE(funcctx);
|
}
|
|
Datum
|
dbms_java_decode_native_compiler_option(PG_FUNCTION_ARGS)
|
{
|
char *optionName;
|
char *value;
|
|
if (PG_ARGISNULL(0))
|
PG_RETURN_TEXT_P(cstring_to_text("<malformed compiler option>"));
|
optionName = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
value = PG_ARGISNULL(1) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(1));
|
if (strcmp(optionName, "exclude") == 0)
|
PG_RETURN_TEXT_P(cstring_to_text(value));
|
PG_RETURN_TEXT_P(cstring_to_text("<malformed compiler option>"));
|
}
|
|
static bool
|
propertyFetch(const char *name, std::string *value)
|
{
|
Oid argtypes[2] = {TEXTOID, TEXTOID};
|
Datum values[2];
|
char nulls[2] = {' ', ' '};
|
const char *sql =
|
"SELECT value FROM pg_catalog.dbms_java_property "
|
"WHERE schema_name = $1 AND name = $2";
|
MemoryContext caller = CurrentMemoryContext;
|
bool found = false;
|
bool isnull = true;
|
std::string schema = exportSchema();
|
|
values[0] = CStringGetTextDatum(schema.c_str());
|
values[1] = CStringGetTextDatum(name);
|
SPI_connect();
|
int rc = SPI_execute_with_args(sql, 2, argtypes, values, nulls, true, 1);
|
if (rc == SPI_OK_SELECT && SPI_processed == 1)
|
{
|
Datum d = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
|
if (!isnull)
|
{
|
char *raw = TextDatumGetCString(d);
|
MemoryContextSwitchTo(caller);
|
*value = raw;
|
pfree(raw);
|
found = true;
|
}
|
}
|
SPI_finish();
|
return found;
|
}
|
|
static void
|
propertyStore(const char *name, const char *value)
|
{
|
Oid argtypes[3] = {TEXTOID, TEXTOID, TEXTOID};
|
Datum values[3];
|
char nulls[3] = {' ', ' ', ' '};
|
const char *del =
|
"DELETE FROM pg_catalog.dbms_java_property WHERE schema_name = $1 AND name = $2";
|
const char *ins =
|
"INSERT INTO pg_catalog.dbms_java_property (schema_name, name, value) VALUES ($1, $2, $3)";
|
std::string schema = exportSchema();
|
|
values[0] = CStringGetTextDatum(schema.c_str());
|
values[1] = CStringGetTextDatum(name);
|
values[2] = CStringGetTextDatum(value);
|
SPI_connect();
|
SPI_execute_with_args(del, 2, argtypes, values, nulls, false, 0);
|
SPI_execute_with_args(ins, 3, argtypes, values, nulls, false, 0);
|
SPI_finish();
|
}
|
|
static void
|
propertyClearSchema(void)
|
{
|
Oid argtypes[1] = {TEXTOID};
|
Datum values[1];
|
char nulls[1] = {' '};
|
const char *sql =
|
"DELETE FROM pg_catalog.dbms_java_property WHERE schema_name = $1";
|
std::string schema = exportSchema();
|
|
values[0] = CStringGetTextDatum(schema.c_str());
|
SPI_connect();
|
SPI_execute_with_args(sql, 1, argtypes, values, nulls, false, 0);
|
SPI_finish();
|
}
|
|
static bool
|
cmdlineClass(const char *cmdline, std::string *className)
|
{
|
const char *p = cmdline;
|
|
if (p == NULL)
|
return false;
|
while (*p == ' ' || *p == '\t')
|
p++;
|
if (*p == '\0')
|
return false;
|
while (*p != '\0')
|
{
|
std::string tok;
|
size_t i;
|
|
while (*p == ' ' || *p == '\t')
|
p++;
|
if (*p == '\0')
|
break;
|
while (*p != '\0' && *p != ' ' && *p != '\t')
|
tok.push_back(*p++);
|
if (tok.empty())
|
break;
|
if (tok[0] == '-')
|
{
|
if (tok == "-classpath" || tok == "-cp")
|
{
|
while (*p == ' ' || *p == '\t')
|
p++;
|
while (*p != '\0' && *p != ' ' && *p != '\t')
|
p++;
|
}
|
continue;
|
}
|
for (i = 0; i < tok.size(); i++)
|
{
|
if (tok[i] == '.')
|
tok[i] = '/';
|
}
|
*className = tok;
|
return true;
|
}
|
return false;
|
}
|
|
static Datum
|
runjavaCommon(PG_FUNCTION_ARGS, bool clear)
|
{
|
char *cmdline;
|
std::string className;
|
char *err;
|
|
if (PG_ARGISNULL(0))
|
PG_RETURN_TEXT_P(cstring_to_text("no class or jar name"));
|
cmdline = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
if (!cmdlineClass(cmdline, &className))
|
{
|
pfree(cmdline);
|
PG_RETURN_TEXT_P(cstring_to_text("no class or jar name"));
|
}
|
pfree(cmdline);
|
if (clear)
|
rudb_java_reset_session();
|
err = rudb_java_run_main(className.c_str());
|
if (err != NULL)
|
{
|
text *msg = cstring_to_text(err);
|
|
pfree(err);
|
PG_RETURN_TEXT_P(msg);
|
}
|
PG_RETURN_NULL();
|
}
|
|
static void
|
propertyClear(const char *name)
|
{
|
Oid argtypes[2] = {TEXTOID, TEXTOID};
|
Datum values[2];
|
char nulls[2] = {' ', ' '};
|
const char *sql =
|
"DELETE FROM pg_catalog.dbms_java_property WHERE schema_name = $1 AND name = $2";
|
std::string schema = exportSchema();
|
|
values[0] = CStringGetTextDatum(schema.c_str());
|
values[1] = CStringGetTextDatum(name);
|
SPI_connect();
|
SPI_execute_with_args(sql, 2, argtypes, values, nulls, false, 0);
|
SPI_finish();
|
}
|
|
Datum
|
dbms_java_set_property(PG_FUNCTION_ARGS)
|
{
|
char *name;
|
char *value;
|
|
if (PG_ARGISNULL(0))
|
PG_RETURN_NULL();
|
name = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
value = PG_ARGISNULL(1) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(1));
|
propertyStore(name, value);
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_get_property(PG_FUNCTION_ARGS)
|
{
|
std::string value;
|
char *name;
|
|
if (PG_ARGISNULL(0))
|
PG_RETURN_NULL();
|
name = text_to_cstring(PG_GETARG_TEXT_PP(0));
|
if (!propertyFetch(name, &value))
|
PG_RETURN_NULL();
|
PG_RETURN_TEXT_P(cstring_to_text(value.c_str()));
|
}
|
|
Datum
|
dbms_java_remove_property(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0))
|
PG_RETURN_NULL();
|
propertyClear(text_to_cstring(PG_GETARG_TEXT_PP(0)));
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_show_property(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_set_preference(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
PG_RETURN_VOID();
|
}
|
|
static void propertyClearSchema(void);
|
static Datum runjavaCommon(PG_FUNCTION_ARGS, bool clear);
|
|
Datum
|
dbms_java_endsession(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
rudb_java_reset_session();
|
PG_RETURN_TEXT_P(cstring_to_text("Java session ended."));
|
}
|
|
Datum
|
dbms_java_endsession_and_related_state(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
rudb_java_reset_session();
|
rudb_java_clear_related();
|
rudb_java_sql_output_clear();
|
propertyClearSchema();
|
PG_RETURN_TEXT_P(cstring_to_text("Java session and related state ended."));
|
}
|
|
Datum
|
dbms_java_runjava(PG_FUNCTION_ARGS)
|
{
|
return runjavaCommon(fcinfo, true);
|
}
|
|
Datum
|
dbms_java_runjava_in_current_session(PG_FUNCTION_ARGS)
|
{
|
return runjavaCommon(fcinfo, false);
|
}
|
|
struct SqlOutSpec
|
{
|
std::string id;
|
std::string stmt;
|
std::string bindings;
|
std::string noNewlineStmt;
|
std::string noNewlineBindings;
|
std::string newlineOnlyStmt;
|
std::string newlineOnlyBindings;
|
int maxLen;
|
bool fromStdout;
|
bool fromStderr;
|
bool includeNewlines;
|
bool eager;
|
bool enabled;
|
std::string pendingOut;
|
std::string pendingErr;
|
int lineno;
|
};
|
|
static std::vector<SqlOutSpec> sqlOutSpecs_;
|
|
struct JavaOutSpec
|
{
|
std::string id;
|
std::string className;
|
std::string classSchema;
|
std::string method;
|
std::string bindings;
|
std::string noNewlineMethod;
|
std::string noNewlineBindings;
|
std::string newlineOnlyMethod;
|
std::string newlineOnlyBindings;
|
std::string initStmt;
|
std::string finiStmt;
|
int maxLen;
|
bool fromStdout;
|
bool fromStderr;
|
bool includeNewlines;
|
bool eager;
|
bool enabled;
|
std::string pendingOut;
|
std::string pendingErr;
|
int lineno;
|
};
|
|
static std::vector<JavaOutSpec> javaOutSpecs_;
|
static int javaOutBusy_ = 0;
|
|
struct FileOutSpec
|
{
|
std::string id;
|
std::string path;
|
bool fromStdout;
|
bool fromStderr;
|
bool enabled;
|
};
|
|
static std::vector<FileOutSpec> fileOutSpecs_;
|
static bool trcOn_ = true;
|
|
static std::string
|
argText(PG_FUNCTION_ARGS, int idx)
|
{
|
char *raw;
|
std::string out;
|
|
if (PG_ARGISNULL(idx))
|
return out;
|
raw = text_to_cstring(PG_GETARG_TEXT_PP(idx));
|
out = raw;
|
pfree(raw);
|
return out;
|
}
|
|
static int
|
argNumber(PG_FUNCTION_ARGS, int idx, int fallback)
|
{
|
if (PG_ARGISNULL(idx))
|
return fallback;
|
return DatumGetInt32(DirectFunctionCall1(numeric_int4, PG_GETARG_DATUM(idx)));
|
}
|
|
static SqlOutSpec *
|
sqlOutFind(const std::string &id)
|
{
|
for (size_t i = 0; i < sqlOutSpecs_.size(); i++)
|
{
|
if (sqlOutSpecs_[i].id == id)
|
return &sqlOutSpecs_[i];
|
}
|
return NULL;
|
}
|
|
static std::string
|
sqlOutNotFound(const std::string &id)
|
{
|
return "output to sql specification \"" + id + "\" not found";
|
}
|
|
static std::string
|
colonToDollar(const std::string &stmt)
|
{
|
std::string out;
|
bool inStr = false;
|
|
for (size_t i = 0; i < stmt.size(); i++)
|
{
|
char c = stmt[i];
|
if (c == '\'')
|
inStr = !inStr;
|
if (!inStr && c == ':' && i + 1 < stmt.size() && std::isdigit((unsigned char) stmt[i + 1]))
|
c = '$';
|
out.push_back(c);
|
}
|
return out;
|
}
|
|
static std::vector<std::string>
|
splitTokens(const std::string &bindings)
|
{
|
std::vector<std::string> out;
|
std::string tok;
|
|
for (size_t i = 0; i <= bindings.size(); i++)
|
{
|
char c = i == bindings.size() ? ' ' : bindings[i];
|
if (c == ' ' || c == '\t' || c == ',' || c == '\n')
|
{
|
if (!tok.empty())
|
{
|
for (size_t j = 0; j < tok.size(); j++)
|
tok[j] = (char) std::toupper((unsigned char) tok[j]);
|
out.push_back(tok);
|
tok.clear();
|
}
|
}
|
else
|
tok.push_back(c);
|
}
|
return out;
|
}
|
|
static void
|
sqlOutExec(SqlOutSpec *spec, const std::string &text, bool nl, bool errout, int segno)
|
{
|
std::string stmt = spec->stmt;
|
std::string bindings = spec->bindings;
|
std::string sql;
|
std::vector<std::string> tokens;
|
Oid argtypes[16];
|
Datum values[16];
|
char nulls[16];
|
char *copies[16];
|
int ncopies = 0;
|
int nargs = 0;
|
int i;
|
|
if (nl && text.empty() && !spec->newlineOnlyStmt.empty())
|
{
|
stmt = spec->newlineOnlyStmt;
|
bindings = spec->newlineOnlyBindings;
|
}
|
else if (!nl && !spec->noNewlineStmt.empty())
|
{
|
stmt = spec->noNewlineStmt;
|
bindings = spec->noNewlineBindings;
|
}
|
sql = colonToDollar(stmt);
|
tokens = splitTokens(bindings);
|
for (i = 0; i < (int) tokens.size() && nargs < 16; i++)
|
{
|
const std::string &tok = tokens[i];
|
|
nulls[nargs] = ' ';
|
if (tok == "TEXT" || tok == "ID")
|
{
|
argtypes[nargs] = TEXTOID;
|
copies[ncopies] = pstrdup(tok == "ID" ? spec->id.c_str() : text.c_str());
|
values[nargs] = CStringGetTextDatum(copies[ncopies]);
|
ncopies++;
|
}
|
else
|
{
|
int n = 0;
|
if (tok == "LENGTH")
|
n = (int) text.size();
|
else if (tok == "LINENO")
|
n = spec->lineno;
|
else if (tok == "SEGNO")
|
n = segno;
|
else if (tok == "NL")
|
n = nl ? 1 : 0;
|
else if (tok == "ERROUT")
|
n = errout ? 1 : 0;
|
else
|
{
|
nulls[nargs] = 'n';
|
values[nargs] = (Datum) 0;
|
argtypes[nargs] = TEXTOID;
|
nargs++;
|
continue;
|
}
|
argtypes[nargs] = NUMERICOID;
|
values[nargs] = DirectFunctionCall1(int4_numeric, Int32GetDatum(n));
|
}
|
nargs++;
|
}
|
SPI_connect();
|
SPI_execute_with_args(sql.c_str(), nargs, argtypes, values, nulls, false, 0);
|
SPI_finish();
|
for (i = 0; i < ncopies; i++)
|
pfree(copies[i]);
|
}
|
|
static void
|
sqlOutEmit(SqlOutSpec *spec, const std::string &text, bool nl, bool errout)
|
{
|
int segno = 1;
|
|
if (spec->maxLen <= 0 || text.empty())
|
{
|
sqlOutExec(spec, text, nl, errout, segno);
|
return;
|
}
|
for (size_t pos = 0; pos < text.size(); pos += (size_t) spec->maxLen, segno++)
|
sqlOutExec(spec, text.substr(pos, (size_t) spec->maxLen), nl, errout, segno);
|
}
|
|
static void
|
sqlOutFeedOne(SqlOutSpec *spec, const std::string &text, bool errout)
|
{
|
std::string *pending = errout ? &spec->pendingErr : &spec->pendingOut;
|
std::string buf = *pending + text;
|
size_t i = 0;
|
|
pending->clear();
|
while (i < buf.size())
|
{
|
size_t nl = buf.find('\n', i);
|
std::string line;
|
|
if (nl == std::string::npos)
|
{
|
if (spec->eager)
|
sqlOutEmit(spec, buf.substr(i), false, errout);
|
else
|
*pending = buf.substr(i);
|
break;
|
}
|
line = buf.substr(i, nl - i);
|
if (!line.empty() && line.back() == '\r')
|
line.pop_back();
|
spec->lineno++;
|
if (spec->includeNewlines)
|
line.push_back('\n');
|
sqlOutEmit(spec, line, true, errout);
|
i = nl + 1;
|
}
|
}
|
|
static std::string
|
sqlOutDescribe(const SqlOutSpec &spec)
|
{
|
std::string streams = " output from ";
|
std::string maxs;
|
|
if (spec.fromStdout && spec.fromStderr)
|
streams += "STDOUT and STDERR";
|
else if (spec.fromStdout)
|
streams += "STDOUT";
|
else if (spec.fromStderr)
|
streams += "STDERR";
|
else
|
streams += "neither";
|
if (spec.maxLen <= 0)
|
maxs = " no max line length";
|
else
|
maxs = " max line length " + std::to_string(spec.maxLen);
|
return "Description of output to sql specification named " + spec.id + "\n"
|
+ streams + maxs + "\n"
|
+ "default statement: " + spec.stmt + "\n"
|
+ "bindings: " + spec.bindings + "\n";
|
}
|
|
static JavaOutSpec *
|
javaOutFind(const std::string &id)
|
{
|
for (size_t i = 0; i < javaOutSpecs_.size(); i++)
|
{
|
if (javaOutSpecs_[i].id == id)
|
return &javaOutSpecs_[i];
|
}
|
return NULL;
|
}
|
|
static std::string
|
javaOutNotFound(const std::string &id)
|
{
|
return "output to java specification \"" + id + "\" not found";
|
}
|
|
static bool
|
javaOutClassOk(const std::string &className, const std::string &schema)
|
{
|
std::string sch = schema.empty() ? exportSchema() : schema;
|
Oid argtypes[2] = {TEXTOID, TEXTOID};
|
Datum values[2];
|
char nulls[2] = {' ', ' '};
|
bool found = false;
|
int rc;
|
|
values[0] = CStringGetTextDatum(className.c_str());
|
values[1] = CStringGetTextDatum(sch.c_str());
|
SPI_connect();
|
rc = SPI_execute_with_args(
|
"SELECT 1 FROM pg_catalog.dbms_java_object "
|
"WHERE kind = 'class' AND bytes IS NOT NULL AND short_name = $1 "
|
"AND lower(schema_name) = lower($2) LIMIT 1",
|
2, argtypes, values, nulls, true, 1);
|
found = rc == SPI_OK_SELECT && SPI_processed == 1;
|
if (!found && schema.empty() && sch != "public" && sch != "PUBLIC")
|
{
|
values[1] = CStringGetTextDatum("public");
|
rc = SPI_execute_with_args(
|
"SELECT 1 FROM pg_catalog.dbms_java_object "
|
"WHERE kind = 'class' AND bytes IS NOT NULL AND short_name = $1 "
|
"AND lower(schema_name) = lower($2) LIMIT 1",
|
2, argtypes, values, nulls, true, 1);
|
found = rc == SPI_OK_SELECT && SPI_processed == 1;
|
}
|
SPI_finish();
|
return found;
|
}
|
|
static void
|
javaOutCall(const JavaOutSpec &spec, const std::string &method, const std::string &text)
|
{
|
if (javaOutBusy_ || method.empty())
|
return;
|
javaOutBusy_++;
|
PG_TRY();
|
{
|
rudb_java_call_output(spec.className.c_str(), method.c_str(), text.c_str());
|
}
|
PG_CATCH();
|
{
|
javaOutBusy_--;
|
PG_RE_THROW();
|
}
|
PG_END_TRY();
|
javaOutBusy_--;
|
}
|
|
static void
|
javaOutEmit(JavaOutSpec *spec, const std::string &method, const std::string &text)
|
{
|
if (spec->maxLen <= 0 || text.empty())
|
{
|
javaOutCall(*spec, method, text);
|
return;
|
}
|
for (size_t pos = 0; pos < text.size(); pos += (size_t) spec->maxLen)
|
javaOutCall(*spec, method, text.substr(pos, (size_t) spec->maxLen));
|
}
|
|
static void
|
javaOutFeedOne(JavaOutSpec *spec, const std::string &text, bool errout)
|
{
|
std::string *pending = errout ? &spec->pendingErr : &spec->pendingOut;
|
std::string buf = *pending + text;
|
std::string method = spec->method;
|
size_t i = 0;
|
|
pending->clear();
|
while (i < buf.size())
|
{
|
size_t nl = buf.find('\n', i);
|
std::string line;
|
bool atNl;
|
|
if (nl == std::string::npos)
|
{
|
if (spec->eager && !spec->noNewlineMethod.empty())
|
javaOutEmit(spec, spec->noNewlineMethod, buf.substr(i));
|
else if (spec->eager)
|
javaOutEmit(spec, method, buf.substr(i));
|
else
|
*pending = buf.substr(i);
|
break;
|
}
|
line = buf.substr(i, nl - i);
|
if (!line.empty() && line.back() == '\r')
|
line.pop_back();
|
spec->lineno++;
|
atNl = true;
|
if (spec->includeNewlines)
|
line.push_back('\n');
|
if (atNl && !spec->newlineOnlyMethod.empty())
|
javaOutEmit(spec, spec->newlineOnlyMethod, line);
|
else
|
javaOutEmit(spec, method, line);
|
i = nl + 1;
|
}
|
}
|
|
static std::string
|
javaOutDescribe(const JavaOutSpec &spec)
|
{
|
std::string streams = " output from ";
|
std::string maxs;
|
|
if (spec.fromStdout && spec.fromStderr)
|
streams += "STDOUT and STDERR";
|
else if (spec.fromStdout)
|
streams += "STDOUT";
|
else if (spec.fromStderr)
|
streams += "STDERR";
|
else
|
streams += "neither";
|
if (spec.maxLen <= 0)
|
maxs = " no max line length";
|
else
|
maxs = " max line length " + std::to_string(spec.maxLen);
|
return "Description of output to java specification named " + spec.id + "\n"
|
+ streams + maxs + "\n"
|
+ "class name: " + spec.className + "\n"
|
+ "default method: " + spec.method + "\n"
|
+ "bindings: " + spec.bindings + "\n";
|
}
|
|
static int
|
javaOutActive(void)
|
{
|
for (size_t i = 0; i < javaOutSpecs_.size(); i++)
|
{
|
if (javaOutSpecs_[i].enabled)
|
return 1;
|
}
|
return 0;
|
}
|
|
static FileOutSpec *
|
fileOutFind(const std::string &id)
|
{
|
for (size_t i = 0; i < fileOutSpecs_.size(); i++)
|
{
|
if (fileOutSpecs_[i].id == id)
|
return &fileOutSpecs_[i];
|
}
|
return NULL;
|
}
|
|
static std::string
|
fileOutNotFound(const std::string &id)
|
{
|
return "output to file specification \"" + id + "\" not found";
|
}
|
|
static std::string
|
fileOutShownPath(const std::string &path)
|
{
|
std::string shown = path;
|
|
if (shown.size() > 6)
|
shown.resize(shown.size() - 6);
|
return ",'" + shown;
|
}
|
|
static std::string
|
fileOutDescribe(const FileOutSpec &spec)
|
{
|
std::string streams = " output from ";
|
|
if (spec.fromStdout && spec.fromStderr)
|
streams += "STDOUT and STDERR";
|
else if (spec.fromStdout)
|
streams += "STDOUT";
|
else if (spec.fromStderr)
|
streams += "STDERR";
|
else
|
streams += "neither";
|
return "Description of output to file specification named " + spec.id + "\n"
|
+ streams + "\n"
|
+ "file path: " + fileOutShownPath(spec.path) + "\n";
|
}
|
|
static void
|
fileOutAppend(const std::string &path, const std::string &body)
|
{
|
FILE *out;
|
|
if (path.empty() || body.empty())
|
return;
|
out = fopen(path.c_str(), "ab");
|
if (out == NULL)
|
return;
|
fwrite(body.data(), 1, body.size(), out);
|
fclose(out);
|
}
|
|
static int
|
fileOutActive(void)
|
{
|
for (size_t i = 0; i < fileOutSpecs_.size(); i++)
|
{
|
if (fileOutSpecs_[i].enabled)
|
return 1;
|
}
|
return 0;
|
}
|
|
extern "C" void
|
rudb_java_sql_output(const char *text, int text_len, int errout)
|
{
|
std::string body;
|
|
if (text != NULL && text_len > 0)
|
body.assign(text, text_len);
|
for (size_t i = 0; i < sqlOutSpecs_.size(); i++)
|
{
|
SqlOutSpec *spec = &sqlOutSpecs_[i];
|
if (!spec->enabled)
|
continue;
|
if (errout && !spec->fromStderr)
|
continue;
|
if (!errout && !spec->fromStdout)
|
continue;
|
sqlOutFeedOne(spec, body, errout != 0);
|
}
|
for (size_t i = 0; i < javaOutSpecs_.size(); i++)
|
{
|
JavaOutSpec *spec = &javaOutSpecs_[i];
|
if (!spec->enabled)
|
continue;
|
if (errout && !spec->fromStderr)
|
continue;
|
if (!errout && !spec->fromStdout)
|
continue;
|
javaOutFeedOne(spec, body, errout != 0);
|
}
|
for (size_t i = 0; i < fileOutSpecs_.size(); i++)
|
{
|
FileOutSpec *spec = &fileOutSpecs_[i];
|
if (!spec->enabled)
|
continue;
|
if (errout && !spec->fromStderr)
|
continue;
|
if (!errout && !spec->fromStdout)
|
continue;
|
fileOutAppend(spec->path, body);
|
}
|
}
|
|
extern "C" int
|
rudb_java_sql_output_active(void)
|
{
|
for (size_t i = 0; i < sqlOutSpecs_.size(); i++)
|
{
|
if (sqlOutSpecs_[i].enabled)
|
return 1;
|
}
|
if (javaOutActive())
|
return 1;
|
return fileOutActive();
|
}
|
|
extern "C" void
|
rudb_java_sql_output_clear(void)
|
{
|
sqlOutSpecs_.clear();
|
javaOutSpecs_.clear();
|
fileOutSpecs_.clear();
|
}
|
|
Datum
|
dbms_java_set_output_to_sql(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
SqlOutSpec spec;
|
SqlOutSpec *old;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec.id = id;
|
spec.stmt = argText(fcinfo, 1);
|
spec.bindings = argText(fcinfo, 2);
|
spec.noNewlineStmt = argText(fcinfo, 3);
|
spec.noNewlineBindings = argText(fcinfo, 4);
|
spec.newlineOnlyStmt = argText(fcinfo, 5);
|
spec.newlineOnlyBindings = argText(fcinfo, 6);
|
spec.maxLen = argNumber(fcinfo, 7, 0);
|
spec.fromStdout = argNumber(fcinfo, 9, 1) != 0;
|
spec.fromStderr = argNumber(fcinfo, 10, 1) != 0;
|
spec.includeNewlines = argNumber(fcinfo, 11, 0) != 0;
|
spec.eager = argNumber(fcinfo, 12, 0) != 0;
|
spec.enabled = true;
|
spec.lineno = 0;
|
old = sqlOutFind(id);
|
if (old != NULL && argNumber(fcinfo, 8, 1) == 0)
|
PG_RETURN_TEXT_P(cstring_to_text("specification with this name already exists"));
|
if (old != NULL)
|
*old = spec;
|
else
|
sqlOutSpecs_.push_back(spec);
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_remove_output_to_sql(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
for (size_t i = 0; i < sqlOutSpecs_.size(); i++)
|
{
|
if (sqlOutSpecs_[i].id == id)
|
{
|
sqlOutSpecs_.erase(sqlOutSpecs_.begin() + i);
|
PG_RETURN_NULL();
|
}
|
}
|
PG_RETURN_TEXT_P(cstring_to_text(sqlOutNotFound(id).c_str()));
|
}
|
|
Datum
|
dbms_java_enable_output_to_sql(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
SqlOutSpec *spec;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec = sqlOutFind(id);
|
if (spec == NULL)
|
PG_RETURN_TEXT_P(cstring_to_text(sqlOutNotFound(id).c_str()));
|
spec->enabled = true;
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_disable_output_to_sql(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
SqlOutSpec *spec;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec = sqlOutFind(id);
|
if (spec == NULL)
|
PG_RETURN_TEXT_P(cstring_to_text(sqlOutNotFound(id).c_str()));
|
spec->enabled = false;
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_query_output_to_sql(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
SqlOutSpec *spec;
|
std::string text;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec = sqlOutFind(id);
|
if (spec == NULL)
|
PG_RETURN_TEXT_P(cstring_to_text(sqlOutNotFound(id).c_str()));
|
text = sqlOutDescribe(*spec);
|
PG_RETURN_TEXT_P(cstring_to_text(text.c_str()));
|
}
|
|
Datum
|
dbms_java_set_output_to_java(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
JavaOutSpec spec;
|
JavaOutSpec *old;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec.id = id;
|
spec.className = argText(fcinfo, 1);
|
spec.classSchema = argText(fcinfo, 2);
|
spec.method = argText(fcinfo, 3);
|
spec.bindings = argText(fcinfo, 4);
|
spec.noNewlineMethod = argText(fcinfo, 5);
|
spec.noNewlineBindings = argText(fcinfo, 6);
|
spec.newlineOnlyMethod = argText(fcinfo, 7);
|
spec.newlineOnlyBindings = argText(fcinfo, 8);
|
spec.maxLen = argNumber(fcinfo, 9, 0);
|
spec.fromStdout = argNumber(fcinfo, 11, 1) != 0;
|
spec.fromStderr = argNumber(fcinfo, 12, 1) != 0;
|
spec.includeNewlines = argNumber(fcinfo, 13, 0) != 0;
|
spec.eager = argNumber(fcinfo, 14, 0) != 0;
|
spec.initStmt = argText(fcinfo, 15);
|
spec.finiStmt = argText(fcinfo, 16);
|
spec.enabled = true;
|
spec.lineno = 0;
|
if (!javaOutClassOk(spec.className, spec.classSchema))
|
PG_RETURN_TEXT_P(cstring_to_text("class not found or not accessible"));
|
old = javaOutFind(id);
|
if (old != NULL && argNumber(fcinfo, 10, 1) == 0)
|
PG_RETURN_TEXT_P(cstring_to_text("specification with this name already exists"));
|
if (old != NULL)
|
*old = spec;
|
else
|
javaOutSpecs_.push_back(spec);
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_remove_output_to_java(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
for (size_t i = 0; i < javaOutSpecs_.size(); i++)
|
{
|
if (javaOutSpecs_[i].id == id)
|
{
|
javaOutSpecs_.erase(javaOutSpecs_.begin() + i);
|
PG_RETURN_NULL();
|
}
|
}
|
PG_RETURN_TEXT_P(cstring_to_text(javaOutNotFound(id).c_str()));
|
}
|
|
Datum
|
dbms_java_enable_output_to_java(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
JavaOutSpec *spec;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec = javaOutFind(id);
|
if (spec == NULL)
|
PG_RETURN_TEXT_P(cstring_to_text(javaOutNotFound(id).c_str()));
|
spec->enabled = true;
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_disable_output_to_java(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
JavaOutSpec *spec;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec = javaOutFind(id);
|
if (spec == NULL)
|
PG_RETURN_TEXT_P(cstring_to_text(javaOutNotFound(id).c_str()));
|
spec->enabled = false;
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_query_output_to_java(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
JavaOutSpec *spec;
|
std::string text;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec = javaOutFind(id);
|
if (spec == NULL)
|
PG_RETURN_TEXT_P(cstring_to_text(javaOutNotFound(id).c_str()));
|
text = javaOutDescribe(*spec);
|
PG_RETURN_TEXT_P(cstring_to_text(text.c_str()));
|
}
|
|
Datum
|
dbms_java_set_output_to_file(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
FileOutSpec spec;
|
FileOutSpec *old;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec.id = id;
|
spec.path = argText(fcinfo, 1);
|
spec.fromStdout = argNumber(fcinfo, 3, 1) != 0;
|
spec.fromStderr = argNumber(fcinfo, 4, 1) != 0;
|
spec.enabled = true;
|
old = fileOutFind(id);
|
if (old != NULL && argNumber(fcinfo, 2, 1) == 0)
|
PG_RETURN_TEXT_P(cstring_to_text("specification with this name already exists"));
|
if (old != NULL)
|
*old = spec;
|
else
|
fileOutSpecs_.push_back(spec);
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_remove_output_to_file(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
for (size_t i = 0; i < fileOutSpecs_.size(); i++)
|
{
|
if (fileOutSpecs_[i].id == id)
|
{
|
fileOutSpecs_.erase(fileOutSpecs_.begin() + i);
|
PG_RETURN_NULL();
|
}
|
}
|
PG_RETURN_TEXT_P(cstring_to_text(fileOutNotFound(id).c_str()));
|
}
|
|
Datum
|
dbms_java_enable_output_to_file(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
FileOutSpec *spec;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec = fileOutFind(id);
|
if (spec == NULL)
|
PG_RETURN_TEXT_P(cstring_to_text(fileOutNotFound(id).c_str()));
|
spec->enabled = true;
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_disable_output_to_file(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
FileOutSpec *spec;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec = fileOutFind(id);
|
if (spec == NULL)
|
PG_RETURN_TEXT_P(cstring_to_text(fileOutNotFound(id).c_str()));
|
spec->enabled = false;
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_query_output_to_file(PG_FUNCTION_ARGS)
|
{
|
std::string id = argText(fcinfo, 0);
|
FileOutSpec *spec;
|
std::string text;
|
|
if (id.empty())
|
PG_RETURN_TEXT_P(cstring_to_text("ID must not be null"));
|
spec = fileOutFind(id);
|
if (spec == NULL)
|
PG_RETURN_TEXT_P(cstring_to_text(fileOutNotFound(id).c_str()));
|
text = fileOutDescribe(*spec);
|
PG_RETURN_TEXT_P(cstring_to_text(text.c_str()));
|
}
|
|
Datum
|
dbms_java_initialize_output_to_file(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_finalize_output_to_file(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_enable_output_to_trc(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
trcOn_ = true;
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_disable_output_to_trc(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
trcOn_ = false;
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_query_output_to_trc(PG_FUNCTION_ARGS)
|
{
|
(void) fcinfo;
|
if (trcOn_)
|
PG_RETURN_TEXT_P(cstring_to_text("Output to trc is enabled"));
|
PG_RETURN_TEXT_P(cstring_to_text("Output to trc is disabled"));
|
}
|
|
static void
|
jarArgsOrNull(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
|
DbmsJava::failJava("java.lang.NullPointerException");
|
}
|
|
Datum
|
dbms_java_jar_digest(PG_FUNCTION_ARGS)
|
{
|
jarArgsOrNull(fcinfo);
|
DbmsJava::missingJar();
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_jar_digest_bytes(PG_FUNCTION_ARGS)
|
{
|
jarArgsOrNull(fcinfo);
|
DbmsJava::missingJar();
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_set_verifier(PG_FUNCTION_ARGS)
|
{
|
int flag;
|
|
DbmsJava::requireVerifier();
|
if (PG_ARGISNULL(0))
|
DbmsJava::failJava("java.lang.NullPointerException");
|
flag = DatumGetInt32(DirectFunctionCall1(numeric_int4, PG_GETARG_DATUM(0)));
|
DbmsJava::verifierFlag_ = flag;
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_set_system_class_loading(PG_FUNCTION_ARGS)
|
{
|
int flag;
|
|
DbmsJava::requireVerifier();
|
if (PG_ARGISNULL(0))
|
DbmsJava::failJava("java.lang.NullPointerException");
|
flag = DatumGetInt32(DirectFunctionCall1(numeric_int4, PG_GETARG_DATUM(0)));
|
DbmsJava::systemLoading_ = flag;
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_set_execute_privilege(PG_FUNCTION_ARGS)
|
{
|
char *objectName;
|
char *objectSchema;
|
char *objectType;
|
char *grantee;
|
int grantFlag;
|
|
if (PG_ARGISNULL(3))
|
DbmsJava::failJava("java.lang.NullPointerException");
|
objectName = PG_ARGISNULL(0) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(0));
|
objectSchema = PG_ARGISNULL(1) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(1));
|
objectType = PG_ARGISNULL(2) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(2));
|
grantee = text_to_cstring(PG_GETARG_TEXT_PP(3));
|
grantFlag = PG_ARGISNULL(4) ? 0 : DatumGetInt32(DirectFunctionCall1(numeric_int4, PG_GETARG_DATUM(4)));
|
DbmsJava::rememberExec(objectName, objectSchema, objectType, grantee, grantFlag);
|
pfree(objectName);
|
pfree(objectSchema);
|
pfree(objectType);
|
pfree(grantee);
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_set_runtime_exec_credentials(PG_FUNCTION_ARGS)
|
{
|
bool three = PG_NARGS() == 3;
|
int osIdx = three ? 1 : 0;
|
int passIdx = three ? 2 : 1;
|
bool osNull;
|
bool passNull;
|
char *osUser = NULL;
|
char *osPass = NULL;
|
bool unbind;
|
const char *schemaName = "";
|
char *dbuser = NULL;
|
|
if (three)
|
{
|
dbuser = PG_ARGISNULL(0) ? pstrdup("") : text_to_cstring(PG_GETARG_TEXT_PP(0));
|
DbmsJava::credRequireUser(dbuser);
|
schemaName = dbuser;
|
}
|
DbmsJava::credRequireSuper();
|
osNull = PG_ARGISNULL(osIdx);
|
passNull = PG_ARGISNULL(passIdx);
|
if (!osNull)
|
osUser = text_to_cstring(PG_GETARG_TEXT_PP(osIdx));
|
if (!passNull)
|
osPass = text_to_cstring(PG_GETARG_TEXT_PP(passIdx));
|
unbind = (osNull && passNull)
|
|| (osUser != NULL && osPass != NULL && osUser[0] == '\0' && osPass[0] == '\0');
|
if (osPass != NULL)
|
pfree(osPass);
|
DbmsJava::credStore(schemaName, osNull ? "" : osUser, unbind);
|
if (osUser != NULL)
|
pfree(osUser);
|
if (dbuser != NULL)
|
pfree(dbuser);
|
PG_RETURN_VOID();
|
}
|
|
static char *
|
moduleText(FunctionCallInfo fcinfo, int idx, bool *isnull)
|
{
|
if (PG_ARGISNULL(idx))
|
{
|
*isnull = true;
|
return NULL;
|
}
|
*isnull = false;
|
return text_to_cstring(PG_GETARG_TEXT_PP(idx));
|
}
|
|
static char *
|
moduleSchema(FunctionCallInfo fcinfo, bool two, int idx)
|
{
|
bool isnull = false;
|
char *schema;
|
|
if (!two)
|
return GetUserNameFromId(GetUserId(), false);
|
schema = moduleText(fcinfo, idx, &isnull);
|
if (isnull || schema[0] == '\0' || !DbmsJava::moduleSchemaOk(schema))
|
DbmsJava::moduleNpe();
|
return schema;
|
}
|
|
static void
|
moduleAct(FunctionCallInfo fcinfo, const char *kind)
|
{
|
bool two = PG_NARGS() == 2;
|
bool modNull = false;
|
char *moduleName = moduleText(fcinfo, 0, &modNull);
|
char *schema = moduleSchema(fcinfo, two, 1);
|
const char *shown = (!modNull && moduleName != NULL && moduleName[0] != '\0')
|
? moduleName : NULL;
|
|
DbmsJava::moduleMissing(kind, shown, schema);
|
}
|
|
Datum
|
dbms_java_jar_name_from_module(PG_FUNCTION_ARGS)
|
{
|
bool modNull = false;
|
bool schemaNull = false;
|
char *moduleName = moduleText(fcinfo, 0, &modNull);
|
char *schema = moduleText(fcinfo, 1, &schemaNull);
|
|
if (modNull || schemaNull || moduleName[0] == '\0' || schema[0] == '\0')
|
DbmsJava::moduleNpe();
|
if (moduleName != NULL)
|
pfree(moduleName);
|
if (schema != NULL)
|
pfree(schema);
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_hotload_module(PG_FUNCTION_ARGS)
|
{
|
moduleAct(fcinfo, "info");
|
PG_RETURN_VOID();
|
}
|
|
Datum
|
dbms_java_unhotload_module(PG_FUNCTION_ARGS)
|
{
|
moduleAct(fcinfo, "data");
|
PG_RETURN_VOID();
|
}
|
|
static char *
|
ncompArg(FunctionCallInfo fcinfo, int idx)
|
{
|
if (PG_ARGISNULL(idx))
|
return NULL;
|
return text_to_cstring(PG_GETARG_TEXT_PP(idx));
|
}
|
|
static void
|
ncompRequireClass(const char *class_name)
|
{
|
if (class_name == NULL || class_name[0] == '\0')
|
DbmsJava::ncompOra("java.lang.NullPointerException: Class name may not be null");
|
}
|
|
Datum
|
dbms_java_compile_class(PG_FUNCTION_ARGS)
|
{
|
char *className = ncompArg(fcinfo, 0);
|
|
ncompRequireClass(className);
|
PG_RETURN_DATUM(DbmsJava::ncompCount(className));
|
}
|
|
Datum
|
dbms_java_compile_method(PG_FUNCTION_ARGS)
|
{
|
char *className = ncompArg(fcinfo, 0);
|
char *methodName = ncompArg(fcinfo, 1);
|
char *methodSig = ncompArg(fcinfo, 2);
|
std::vector<DbmsJava::NcompMeth> methods;
|
|
ncompRequireClass(className);
|
if (methodName == NULL || methodSig == NULL)
|
DbmsJava::ncompOra("java.lang.NullPointerException");
|
if (!DbmsJava::loadClassMethods(className, &methods))
|
DbmsJava::ncompMissingClass(className);
|
if (!DbmsJava::ncompHasName(methods, methodName))
|
DbmsJava::ncompNoMethod(className, methodName, "()");
|
PG_RETURN_DATUM(DirectFunctionCall1(int4_numeric, Int32GetDatum(0)));
|
}
|
|
Datum
|
dbms_java_uncompile_class(PG_FUNCTION_ARGS)
|
{
|
char *className = ncompArg(fcinfo, 0);
|
|
ncompRequireClass(className);
|
PG_RETURN_DATUM(DbmsJava::ncompCount(className));
|
}
|
|
Datum
|
dbms_java_uncompile_method(PG_FUNCTION_ARGS)
|
{
|
char *className = ncompArg(fcinfo, 0);
|
char *methodName = ncompArg(fcinfo, 1);
|
char *methodSig = ncompArg(fcinfo, 2);
|
std::vector<DbmsJava::NcompMeth> methods;
|
std::string params;
|
|
ncompRequireClass(className);
|
if (methodName == NULL || methodSig == NULL)
|
DbmsJava::ncompOra("java.lang.NullPointerException");
|
if (!DbmsJava::loadClassMethods(className, &methods))
|
DbmsJava::ncompMissingClass(className);
|
if (DbmsJava::ncompHasExact(methods, methodName, methodSig))
|
PG_RETURN_DATUM(DirectFunctionCall1(int4_numeric, Int32GetDatum(1)));
|
if (DbmsJava::ncompHasName(methods, methodName))
|
params = DbmsJava::jniParams(methodSig);
|
else
|
params = "()";
|
DbmsJava::ncompNoMethod(className, methodName, params.c_str());
|
PG_RETURN_NULL();
|
}
|
|
Datum
|
dbms_java_dump_native_machine_code(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2))
|
DbmsJava::ncompOra("java.lang.NullPointerException");
|
DbmsJava::ncompOra("java.lang.ClassCastException");
|
PG_RETURN_VOID();
|
}
|
|
static const char *
|
jmxText(FunctionCallInfo fcinfo, int idx)
|
{
|
char *raw;
|
|
if (PG_NARGS() <= idx || PG_ARGISNULL(idx))
|
return NULL;
|
raw = text_to_cstring(PG_GETARG_TEXT_PP(idx));
|
if (raw[0] == '\0')
|
{
|
pfree(raw);
|
return NULL;
|
}
|
return raw;
|
}
|
|
static bool
|
jmxPermitted(const char *user_name)
|
{
|
Oid argtypes[1] = {TEXTOID};
|
Datum values[1];
|
char nulls[1] = {' '};
|
Oid saveUser;
|
int saveSec;
|
volatile bool granted = false;
|
|
if (superuser())
|
return true;
|
values[0] = CStringGetTextDatum(user_name);
|
GetUserIdAndSecContext(&saveUser, &saveSec);
|
SetUserIdAndSecContext(BOOTSTRAP_SUPERUSERID,
|
saveSec | SECURITY_LOCAL_USERID_CHANGE);
|
PG_TRY();
|
{
|
if (SPI_connect() != SPI_OK_CONNECT)
|
elog(ERROR, "dbms_java: SPI не открыт");
|
if (SPI_execute_with_args(
|
"SELECT 1 FROM pg_catalog.dbms_java_policy "
|
"WHERE grantee = $1 AND kind = 'GRANT' AND enabled "
|
"AND perm_type = 'SYS:java.lang.RuntimePermission' "
|
"AND perm_name = 'accessClassInPackage.jdk.internal.agent' "
|
"LIMIT 1",
|
1, argtypes, values, nulls, true, 1) == SPI_OK_SELECT
|
&& SPI_processed == 1)
|
granted = true;
|
SPI_finish();
|
}
|
PG_CATCH();
|
{
|
SetUserIdAndSecContext(saveUser, saveSec);
|
PG_RE_THROW();
|
}
|
PG_END_TRY();
|
SetUserIdAndSecContext(saveUser, saveSec);
|
return granted;
|
}
|
|
static void
|
jmxDenied(const char *user_name)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
|
errmsg("ORA-29532: Java call terminated by uncaught Java exception: java.security.AccessControlException: the Permission (\"java.lang.RuntimePermission\" \"accessClassInPackage.jdk.internal.agent\") has not been granted to %s. The PL/SQL to grant this is dbms_java.grant_permission( '%s', 'SYS:java.lang.RuntimePermission', 'accessClassInPackage.jdk.internal.agent', '' )",
|
user_name, user_name)));
|
}
|
|
Datum
|
dbms_java_start_jmx_agent(PG_FUNCTION_ARGS)
|
{
|
const char *port = jmxText(fcinfo, 0);
|
const char *ssl = jmxText(fcinfo, 1);
|
const char *auth = jmxText(fcinfo, 2);
|
char *user = GetUserNameFromId(GetUserId(), false);
|
char userName[NAMEDATALEN];
|
|
strlcpy(userName, user != NULL ? user : "", sizeof(userName));
|
if (user != NULL)
|
pfree(user);
|
if (!jmxPermitted(userName))
|
jmxDenied(userName);
|
rudb_java_start_jmx(port, ssl, auth);
|
PG_RETURN_VOID();
|
}
|
|
}
|