summaryrefslogtreecommitdiff
path: root/src/wrapper.c
blob: 7cb52e34a63ff4084f24aa6a3ddec72282fb3ded (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* 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);
	
	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");
#endif
	unsetenv(LUA_INIT);
	
	L = luaL_newstate();
	if (L == NULL) {
		return EXIT_FAILURE;
	}
	
	parg.retcode = 0;
	
	success = lua_cpcall(L, &protected_main, &parg);
	
	lua_close(L);
	
	return ((success == 0) && (parg.retcode == 0)) ? EXIT_SUCCESS :
		((success == 0) ? parg.retcode : EXIT_FAILURE);
}