summaryrefslogtreecommitdiffhomepage
path: root/main.c
blob: ebe6bfeda0ab0871da08a954fb259176f9d90472 (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
#include <string.h>
#include <sys/epoll.h>

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

#include "plop.h"

/// Standard entry point for the program.
/// \param argc Argument count
/// \param argv Argument array
/// \return Error code
int main(int argc, char ** argv)
{
	lua_State * L = luaL_newstate();
	luaL_openlibs(L);

	if (3 != argc)
	{
		return 1; // TODO: Document error codes/print usage information
	}

	if (LUA_OK != load_handler(L, argv[2]))
	{
		return 2; // TODO: Document error codes/print usage information
	}

	const int efd = epoll_create1(0);

	if (-1 == efd)
	{
		return 3; // TODO: Handle errors properly
	}

	struct epoll_event e;
	e.events = EPOLLIN;
	e.data.ptr = NULL; // TODO: Consider putting server's Lua state in here?
	const int server = make_server(NULL, argv[1]); // TODO: Check server's fd before ctl?

	if (-1 == epoll_ctl(efd, EPOLL_CTL_ADD, server, &e))
	{
		return 4; // TODO: Handle errors properly
	}

	static const int MAX_EVENTS = 20;
	struct epoll_event events[MAX_EVENTS];

	while (1)
	{
		int evc = epoll_wait(efd, events, MAX_EVENTS, -1);

		if (-1 == evc)
		{
			return 5; // TODO: Handle errors properly
		}

		for (int i = 0; i < evc; ++i)
		{
			if (NULL == events[i].data.ptr)
			{
				if (-1 == handle_server(L, efd, server))
				{
					return 6; // TODO: Handle errors properly
				}
			}
			else
			{
				if (-1 == handle_client(L, &events[i]))
				{
					return 7; // TODO: Handle errors properly
				}
			}
		}
	}
}