From 1b684971c3b591538c3ba0d3343ec76559f10203 Mon Sep 17 00:00:00 2001 From: Johnny Richard Date: Thu, 7 Apr 2022 14:49:44 +0200 Subject: server.c: Move accept syscall to server_listen function --- server.c | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) (limited to 'server.c') diff --git a/server.c b/server.c index d7edb04..f8068aa 100644 --- a/server.c +++ b/server.c @@ -1,11 +1,32 @@ +/* + * Papo IRC Server + * Copyright (C) 2021 Johnny Richard + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ #include "server.h" #include #include #include +#include #include #include +#define BUFFER_SIZE 1024 +#define EXIT_COMMAND "exit" + server_t server_create(uint32_t port) { @@ -39,3 +60,46 @@ server_create(uint32_t port) return (server_t) { .fd = server_fd }; } + +void +server_listen(server_t *server) +{ + struct sockaddr_in client; + socklen_t client_len = sizeof(client); + + server->running = true; + + while (server->running) { + int client_fd = accept(server->fd, (struct sockaddr *) &client, &client_len); + if (client_fd == -1) { + perror("[ERROR] could not accept connection"); + close(server->fd); + exit(EXIT_FAILURE); + } + while (true) { + char client_buf[BUFFER_SIZE]; + memset(client_buf, 0, BUFFER_SIZE); + + if (recv(client_fd, client_buf, BUFFER_SIZE, 0) == -1) { + perror("[ERROR] could not read data from client"); + continue; + } + + if (!strncasecmp(client_buf, EXIT_COMMAND, strlen(EXIT_COMMAND) - 1)) { + puts("[INFO] exiting program. bye bye!"); + close(client_fd); + close(server->fd); + exit(EXIT_SUCCESS); + } + + if (send(client_fd, client_buf, BUFFER_SIZE, 0) == -1) { + perror("[ERROR] could not send data to client"); + continue; + } + } + + close(client_fd); + close(server->fd); + exit(EXIT_SUCCESS); + } +} -- cgit v1.2.3