PostgreSQLの関数定義

PostgreSQLでは、C言語で新たなSQL関数を定義することができる。
http://www.postgresql.jp/document/pg813doc/html/xfunc-c.html

練習に libselinux と組み合わせて、接続元クライアントのセキュリティコンテキストを取得する関数を作ってみた。

#include <postgres.h>
#include <fmgr.h>
#include <miscadmin.h>
#include <libpq/libpq-be.h>
#include <selinux/selinux.h>

PG_FUNCTION_INFO_V1(security_context);
// text security_context()
// returns the security_context of the connected client process.
Datum security_context(PG_FUNCTION_ARGS) {
security_context_t context;
text *rettext;
int length;

if (getpeercon(MyProcPort->sock, &context))
PG_RETURN_NULL();

length = strlen(context);
rettext = palloc(sizeof(text) + length);
rettext->vl_len = sizeof(text) + length;
strcpy(rettext->vl_dat, context);
freecon(context);

PG_RETURN_TEXT_P(rettext);
}

実際に接続してみた。
[kaigai@ayu ~]$ psql
kaigai=# create function security_context() returns text
as 'sepgsql.so', 'security_context' language c strict;
CREATE FUNCTION
kaigai=# select security_context();
security_context