summaryrefslogtreecommitdiffhomepage
path: root/connection.c
blob: f987d653a58b2544c8f2288a3d6beee59d6a6846 (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
#include "connection.h"

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

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

#include "request.h"

/// Creates new connection.
/// \param L Server's Lua state
/// \param client File descriptor of client's socket
/// \return Pointer to connection or NULL if an error occured
struct connection * connection_new(lua_State * L, const int client)
{
	struct connection * c = malloc(sizeof(struct connection));

	if (NULL == c)
	{
		return NULL;
	}

	memset(c, 0, sizeof(struct connection));

	c->fd = client;
	c->L = lua_newthread(L);
	c->lua_ref = luaL_ref(L, LUA_REGISTRYINDEX);

	return c;
}

/// Clears the state of connection readying it for new request.
/// \param c Connection to clear
void connection_clear(struct connection * c)
{
	if (NULL != c->request)
	{
		free_request(c->request);
	}
}

/// Frees all resources associated with the connection.
/// \param L Server's Lua state
/// \param c Connection to free
void connection_free(lua_State * L, struct connection * c)
{
	connection_clear(c);
	luaL_unref(L, LUA_REGISTRYINDEX, c->lua_ref);
	close(c->fd); // TODO: Check for errors in close()?
	free(c);
}