What is this

This commit is contained in:
akp 2023-11-11 12:03:15 +00:00
parent abc3732e0e
commit 2692a17f4d
3 changed files with 69 additions and 16 deletions

9
firewall-server/mock.py Normal file
View file

@ -0,0 +1,9 @@
import struct
import sys
import time
sys.stdout.write(b"A".decode())
x = "hello world!"
sys.stdout.write(struct.pack("b", len(x)).decode())
sys.stdout.write(x)
sys.stdout.flush()

View file

@ -1,5 +1,5 @@
#include <stdio.h>
#include "sockets.c"
#include "server_includes/sockets.c"
#include <pthread.h>
#include <signal.h>

View file

@ -49,36 +49,80 @@ int open_socket(const char *ip, const char *port, int *res_sd) {
return 0;
}
#define MAX_CHUNK_LENGTH 128
int recv_n(int sd, char *buf, int n) {
char *buf_ptr = buf;
int num_bytes;
int total_received = 0;
while ((num_bytes = recv(sd, buf_ptr, n - total_received, 0)) != 0) {
total_received += num_bytes;
if (num_bytes == -1) {
return 1;
}
if (total_received == n) {
break;
} else if (total_received > n) {
fprintf(stderr, "Unrecoverable: too many bytes read in connection.\n");
exit(2);
} else {
buf_ptr += num_bytes;
}
}
if (total_received != n) {
// not enough bytes received
errno = EPROTO;
return 1;
}
return 0;
}
void handle_connection(int *sdptr) {
int sd = *sdptr;
fprintf(stderr, "TODO: handle connection %d\n", sd);
char *dat = (char *) malloc(sizeof(char) * 128);
fprintf(stderr, "[%d] start\n", sd);
int num_bytes;
while ((num_bytes = recv(sd, dat, MAX_CHUNK_LENGTH, 0)) != 0) {
printf("[DBG %d] got %d bytes\n", sd, num_bytes);
if (num_bytes == -1) {
char *leader = (char *) malloc(sizeof(char) * 2);
if (recv_n(sd, leader, 2) != 0) {
if (errno == EPROTO) {
fprintf(stderr, "[%d] too few bytes supplied\n", sd);
} else {
perror("warning: failed to receive from remote host");
goto cleanup;
}
printf("[LOG %d] %s", sd, dat);
if (num_bytes < MAX_CHUNK_LENGTH) {
break;
}
goto cleanup;
}
char operation = leader[0];
char message_length = leader[1];
fprintf(stderr, "[%d] Operation: %c, message length: %d\n", sd, operation, message_length);
char *data = (char *) malloc(sizeof(char) * message_length);
if (recv_n(sd, data, message_length) != 0) {
if (errno == EPROTO) {
fprintf(stderr, "[%d] too few bytes supplied\n", sd);
} else {
perror("warning: failed to receive from remote host");
}
free(data);
goto cleanup;
}
fprintf(stderr, "[%d] Data: %s\n", sd, data);
if (send(sd, "lmao cool\n", 10, 0) == -1) {
perror("warning: failed to send data to remote host");
goto cleanup;
}
printf("[END %d]\n", sd);
free(data);
cleanup:
free(dat);
free(leader);
printf("[%d] end\n", sd);
if (shutdown(sd, 2) != 0) {
perror("warning: shutdown connection in thread failed");