summaryrefslogtreecommitdiff
path: root/src/wrapper.c
blob: c7ed53509f08e9700aed17d6d1f8607b9f40b7ad (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* 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>

#include "supple_paths.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 */
#if defined BAKE_SUPPLE_PATHS
	setenv("LUA_PATH", SUPPLE_LUA_PATH, 1);
	setenv("LUA_CPATH", SUPPLE_LUA_CPATH, 1);
	unsetenv("SUPPLE_MKDTEMP");
	unsetenv("LUA_INIT");
#elif !defined 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;
		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);
}