libflint/src/network.c

145 lines
3.4 KiB
C
Raw Normal View History

2024-07-08 02:50:28 +00:00
#include <errno.h>
2024-07-08 03:05:32 +00:00
#include <string.h>
2024-07-08 02:50:28 +00:00
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include "lfnetwork.h"
static void sighandler(int s) {
int saved_errno = errno;
while (waitpid(-1, NULL, WNOHANG) > 0);
errno = saved_errno;
}
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
Server *new_server(ServerType type, const char *port, void(handler)(Server *s)) {
Server *s = (Server *)malloc(sizeof(Server));
if (s == NULL) {
return NULL;
}
s->server_type = type;
s->handler = handler;
struct addrinfo *addr = NULL;
if (getaddrinfo(NULL, port, NULL, &addr) != 0) {
free(s);
return NULL;
}
s->port = (int)strtol(port, NULL, 10);
int socktype = 0;
switch (type) {
case SERVERTYPE_TCP:
socktype = SOCK_STREAM;
break;
case SERVERTYPE_UDP:
socktype = SOCK_DGRAM;
break;
}
struct addrinfo *p;
for (p = addr; p != NULL; p = p->ai_next) {
s->fd = socket(AF_INET, socktype, 0);
if (s->fd == -1) {
continue;
}
if (bind(s->fd, p->ai_addr, p->ai_addrlen) != 0) {
close(s->fd);
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "Failed to bind\n");
free(s);
return NULL;
}
freeaddrinfo(addr);
return s;
}
void delete_server(Server *s) {
free(s);
s = NULL;
}
int serve(Server *s, int backlog_size) {
if (listen(s->fd, backlog_size) != 0) {
return 1;
}
struct sigaction sa;
sa.sa_handler = sighandler;
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
fprintf(stderr, "Failed to set sigaction\n");
return 1;
}
printf("Server is waiting for connections on port %d...\n", s->port);
s->handler(s);
return 0;
}
void handler_tcp_echo(Server *s) {
struct sockaddr_storage client_addr;
while (1) {
socklen_t client_addr_sz = sizeof(client_addr);
int new_fd = accept(s->fd, (struct sockaddr *)&client_addr, &client_addr_sz);
if (new_fd == -1) {
printf("failed to accept. Errno: %d\n", errno);
continue;
}
char buf[33];
inet_ntop(client_addr.ss_family, get_in_addr((struct sockaddr *)&client_addr), buf, 32);
printf("Received connection from %s\n", buf);
// Start child process
2024-07-08 03:05:32 +00:00
if (!fork()) {
close(s->fd); // Child doesn't need the initial socket
char recv_buf[256];
int r = recv(new_fd, recv_buf, 256, 0);
if (r == -1) {
fprintf(stderr, "Failed to recv. Errno: %d\n", errno);
goto CHILD_END;
} else if (r == 0) {
fprintf(stderr, "Client closed connection\n");
goto CHILD_END;
}
if (send(new_fd, recv_buf, strlen(recv_buf), 0) == -1) {
fprintf(stderr, "Failed to send echo\n");
}
CHILD_END:
close(new_fd);
_exit(0);
2024-07-08 02:50:28 +00:00
}
// End child process
close(new_fd); // new_fd is not used by the parent
}
}