diff --git a/src/hdbd.c b/src/hdbd.c index e97a5b5..05295f4 100644 --- a/src/hdbd.c +++ b/src/hdbd.c @@ -2,13 +2,20 @@ #include #include #include +#include +#include +#include + +pid_t pid; +int server_sock; +struct sockaddr_un server; +int sockaddr_len; int main() { /* Setup daemon Used this for basic idea => https://en.wikipedia.org/wiki/Daemon_(computing) */ - pid_t pid; pid_t sid; pid = fork(); @@ -33,12 +40,68 @@ int main() { close(STDOUT_FILENO); close(STDERR_FILENO); - /* TODO: Setup HTTP server */ - /* TODO: API needed */ - - /* Actual program */ - char should_close = 0; - while(!should_close) { - sleep(1); + FILE *stdout; + FILE *stderr; + /* TODO: switch to mode 'a' later */ + stdout = fopen("/tmp/out_log.txt", "w"); + stderr = fopen("/tmp/err_log.txt", "w"); + if (out_log == NULL || err_log == NULL) { + return 1; } + + + /* Setup Unix Socket */ + server_sock = socket(AF_UNIX, SOCK_STREAM, 0); + if (sock == -1) { + return 1; + } + + server.sun_family = AF_UNIX; + strcpy(server.sun_path, "/tmp/test_sock"); + unlink(server.sun_path); + sockaddr_len = strlen(server.sun_path) + sizeof(server.sun_family); + + if (bind(server_sock, (struct sockaddr*)&server, sockaddr_len) == -1) { + return 1; + } + + if (listen(server_sock, 3) == -1) { + return 1; + } + + printf("Listening on %s\n", server.sun_path); + + + /* Actual program */ + int client_sock; + char receive_buf[1000]; + char send_buf[1000]; + memset(receive_buf, 0, sizeof receive_buf); + memset(send_buf, 0, sizeof send_buf); + + while(1) { + client_sock = accept(sock, NULL, NULL); + if (sock2 == -1) { + return 1; + } + data_length = recv(sock2, receive_buf, sizeof receive_buf, 0); + if (data_length <= 0) { + strcpy(send_buf, "Failed to receive any data."); + send(client_sock, send_buf, strops_length(send_buf), 0); + close(client_sock); + continue; + } + + if (strops_contains(send_buf, "shutdown now!")) { + strcpy(send_buf, "Shutting down."); + send(client_sock, send_buf, strops_length(send_buf), 0); + close(client_sock); + break; + } + + close(client_sock); + } + + close(server_sock); + return 0; }