summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--Makefile1
-rw-r--r--connection.c52
-rw-r--r--connection.h17
3 files changed, 70 insertions, 0 deletions
diff --git a/Makefile b/Makefile
index c4c3862..9b3c4f3 100644
--- a/Makefile
+++ b/Makefile
@@ -9,6 +9,7 @@ main.o: plop.h request.h
plop.o: plop.h request.h response.h
request.o: request.h
response.o: response.h
+connection.o: connection.h request.h
clean:
rm -f plop *.o
diff --git a/connection.c b/connection.c
new file mode 100644
index 0000000..c7dd151
--- /dev/null
+++ b/connection.c
@@ -0,0 +1,52 @@
+#include "connection.h"
+
+#include <stdlib.h>
+#include <string.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);
+}
diff --git a/connection.h b/connection.h
new file mode 100644
index 0000000..3a7b32a
--- /dev/null
+++ b/connection.h
@@ -0,0 +1,17 @@
+#pragma once
+
+#include <lua.h>
+
+#include "request.h"
+
+struct connection
+{
+ int fd;
+ int lua_ref;
+ lua_State * L;
+ struct request * request;
+};
+
+struct connection * connection_new(lua_State *, const int);
+void connection_clear(struct connection *);
+void connection_free(lua_State *, struct connection *);