/* supple/src/wrapper.c
 *
 * Sandbox (for) Untrusted Procedure Partitioning (in) Lua Engine - Supple
 *
 * Wrapper interpreter to protect and isolate the sandbox code.
 *
 * Copyright 2012 Daniel Silverstone <dsilvers@digital-scurf.org>
 *
 * For licence terms, see COPYING
 *
 */

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct {
	int retcode;
} prot_args;

static int
protected_main(lua_State *L)
{
	prot_args *parg = (prot_args *)lua_touserdata(L, 1);
	
	luaL_openlibs(L);

#ifdef TESTING_SUPPLE
	if (getenv("LUA_INIT") != NULL) {
		if (luaL_dostring(L, getenv("LUA_INIT")) != 0) {
			parg->retcode = 1;
			return 0;
		}
	}
#endif

	lua_getglobal(L, "require");
	lua_pushstring(L, "supple");
	lua_call(L, 1, 1);
	
	lua_getfield(L, -1, "sandbox");
	lua_getfield(L, -1, "run");
	
	lua_call(L, 0, 1);
	
	if (lua_isnumber(L, -1)) {
		parg->retcode = lua_tonumber(L, -1);
	}
	
	return 0;
}

int
main(int argc, char **argv)
{
	prot_args parg;
	lua_State *L;
	int success;
	extern char **environ;

	/* Perform pre-lua-interpreter initialisation */
#if defined BAKE_SUPPLE_PATHS
	environ = NULL;	/* security: clear environment */
	setenv("LUA_PATH", SUPPLE_LUA_PATH, 1);
	setenv("LUA_CPATH", SUPPLE_LUA_CPATH, 1);
#elif !defined TESTING_SUPPLE
	environ = NULL;	/* security: clear environment */
#else
	(void)(environ);	/* unused */
#endif
	
	L = luaL_newstate();
	if (L == NULL) {
		return EXIT_FAILURE;
	}
	
	parg.retcode = 0;
	
	lua_pushcclosure(L, &protected_main, 0);
	lua_pushlightuserdata(L, &parg);
	
	success = lua_pcall(L, 1, 0, 0);

	if (success != 0) {
		size_t l;
		ssize_t n;
		const char *s = lua_tolstring(L, -1, &l);

		n = write(2, s, l);
		if (n == -1) {
			success = 1;
		}
	}

	lua_close(L);
	
	return ((success == 0) && (parg.retcode == 0)) ? EXIT_SUCCESS :
		((success == 0) ? parg.retcode : EXIT_FAILURE);
}
