/* 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;

	/* Perform pre-lua-interpreter initialisation */
#ifndef TESTING_SUPPLE
	unsetenv("LUA_PATH");
	unsetenv("LUA_CPATH");
	unsetenv("SUPPLE_MKDTEMP");
	unsetenv("LUA_INIT");
#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;
		const char *s = lua_tolstring(L, -1, &l);
		write(2, s, l);
        }

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