Files
RN-Praxis2/webserver.c
T
2025-01-12 00:00:59 +01:00

590 lines
19 KiB
C

#include <arpa/inet.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "data.h"
#include "http.h"
#include "util.h"
#include "dht.h"
#include "lookup.h"
#define elif else if
// Getter for environmental DHT sets
#define _PRED_ID (uint16_t)atoi(getenv("PRED_ID"))
#define _PRED_IP getenv("PRED_IP")
#define _PRED_PORT (uint16_t)atoi(getenv("PRED_PORT"))
#define _SUCC_ID (uint16_t)atoi(getenv("SUCC_ID"))
#define _SUCC_IP getenv("SUCC_IP")
#define _SUCC_PORT (uint16_t)atoi(getenv("SUCC_PORT"))
bool _DO_UDP = false;
uint16_t _NODE_ID;
const char *_NODE_IP;
uint16_t _NODE_PORT;
#define MAX_RESOURCES 100
struct tuple resources[MAX_RESOURCES] = {
{"/static/foo", "Foo", sizeof "Foo" - 1},
{"/static/bar", "Bar", sizeof "Bar" - 1},
{"/static/baz", "Baz", sizeof "Baz" - 1}};
typedef enum neighbor{
dunno = -1,
not_res,
res,
res_303,
}neighbor;
uint16_t hash_uri(const char *uri){
char *uri_ptr = (char*)uri;
char dynamic[] = "/dynamic/";
char static_[] = "/static/";
if(strstr(uri, dynamic)) uri_ptr += strlen(dynamic) + 1;
elif(strstr(uri, static_)) uri_ptr += strlen(static_) + 1;
/*
char *it = (char*)uri;
// shift uri_ptr to last '/'
while(*it)
{
if (*it == '/') uri_ptr = it;
it++;
}
// skip last '/'
if (*uri_ptr == '/') uri_ptr++;
if (!*uri_ptr) return -1;
*/
return pseudo_hash((const unsigned char *)uri_ptr, strlen(uri_ptr));
}
neighbor check_neighborhood(uint16_t hash) {
int pre_id = _PRED_ID;
int id = _NODE_ID;
int suc_id = _SUCC_ID;
if(hash > id && hash <= suc_id) return res_303;
if ((pre_id == id && suc_id == id) || (id < pre_id && ((hash > pre_id && hash < 65535)) || hash <= id) || (hash > pre_id && hash <= id))
return res;
if ((id < suc_id && hash > id && hash <= suc_id) || (hash > id || hash <= suc_id))
return not_res;
return dunno;
}
/**
* Sends an HTTP reply to the client based on the received request.
*
* @param conn The file descriptor of the client connection socket.
* @param request A pointer to the struct containing the parsed request
* information.
*/
void send_reply(int conn, struct request *request) {
fprintf(stderr, "\n\n\n---%u---\n", _NODE_ID);
// Create a buffer to hold the HTTP reply
char buffer[HTTP_MAX_SIZE];
char *reply = buffer;
size_t offset = 0;
fprintf(stderr, "Handling %s request for %s (%lu byte payload)\n",
request->method, request->uri, request->payload_length);
printf("Uri: %s\n", request->uri);
uint16_t resource_hash = hash_uri(request->uri);
fprintf(stderr, "Resource hash: %u\n", resource_hash);
if (resource_hash == -1)
{
perror("Pseudo_hash failed - 404\n");
reply = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
offset = strlen(reply);
goto direct_send;
}
neighbor responsible = check_neighborhood(resource_hash);
lookup_request *req = find_lookup(resource_hash);
if(responsible != res){
if(responsible == res_303)
{
perror("Responsible 303 - 303\n");
sprintf(reply, "HTTP/1.1 303 See Other\r\nLocation: http://%s:%d%s\r\nContent-Length: 0\r\n\r\n", _SUCC_IP, _SUCC_PORT, request->uri);
offset = strlen(reply);
}
elif (req == NULL)
{
perror("Not Responsible - 503\n");
sprintf(reply, "HTTP/1.1 503 Service Unavailable\r\nRetry-After: 1\r\nContent-Length: 0\r\n\r\n");
offset = strlen(reply);
lookup_request lookreq;
lookup_request_init(&lookreq, 0, _NODE_ID, ntohl(inet_addr(_NODE_IP)), _NODE_PORT, resource_hash);
call_network(&lookreq, ntohl(inet_addr(_SUCC_IP)), _SUCC_PORT);
}
elif (req->message_type == 1)
{
// DONE: Success
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(req->node_ip.s_addr);
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &addr.sin_addr, ip, INET_ADDRSTRLEN);
perror("Message-type: 1 - 303\n");
sprintf(reply, "HTTP/1.1 303 See Other\r\nLocation: http://%s:%d%s\r\nContent-Length: 0\r\n\r\n", ip, req->node_port, request->uri);
offset = strlen(reply);
}
}
elif (strcmp(request->method, "GET") == 0) {
size_t resource_length;
const char* resource = get(request->uri, resources, MAX_RESOURCES, &resource_length);
if (resource) {
size_t payload_offset = sprintf(reply, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n", resource_length);
memcpy(reply + payload_offset, resource, resource_length);
offset = payload_offset + resource_length;
} else {
reply = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
offset = strlen(reply);
}
} else if (strcmp(request->method, "PUT") == 0) {
// Try to set the requested resource with the given payload in the
// 'resources' array.
if (set(request->uri, request->payload, request->payload_length,
resources, MAX_RESOURCES)) {
reply = "HTTP/1.1 204 No Content\r\n\r\n";
offset = strlen(reply);
} else {
reply = "HTTP/1.1 201 Created\r\nContent-Length: 0\r\n\r\n";
offset = strlen(reply);
}
} else if (strcmp(request->method, "DELETE") == 0) {
// Try to delete the requested resource from the 'resources' array
if (delete (request->uri, resources, MAX_RESOURCES)) {
reply = "HTTP/1.1 204 No Content\r\n\r\n";
offset = strlen(reply);
} else {
reply = "HTTP/1.1 404 Not Found\r\n\r\n";
offset = strlen(reply);
}
} else {
reply = "HTTP/1.1 501 Method Not Supported\r\n\r\n";
offset = strlen(reply);
}
direct_send: // ... do goto, yes you read that right ;)
//offset = strlen(reply);
// Send the reply back to the client
if (send(conn, reply, offset, 0) == -1) {
perror("send");
close(conn);
}
perror("\n\n---HANDLED REQUEST---\n\n");
}
/**
* Processes an incoming packet from the client.
*
* @param conn The socket descriptor representing the connection to the client.
* @param buffer A pointer to the incoming packet's buffer.
* @param n The size of the incoming packet.
*
* @return Returns the number of bytes processed from the packet.
* If the packet is successfully processed and a reply is sent, the
* return value indicates the number of bytes processed. If the packet is
* malformed or an error occurs during processing, the return value is -1.
*
*/
int process_packet(int conn, char *buffer, size_t n) {
struct request request = {
.method = NULL, .uri = NULL, .payload = NULL, .payload_length = -1};
ssize_t bytes_processed = parse_request(buffer, n, &request);
if (bytes_processed > 0) {
send_reply(conn, &request);
// Check the "Connection" header in the request to determine if the
// connection should be kept alive or closed.
const string connection_header = get_header(&request, "Connection");
if (connection_header && strcmp(connection_header, "close")) {
return -1;
}
} else if (bytes_processed == -1) {
// If the request is malformed or an error occurs during processing,
// send a 400 Bad Request response to the client.
const string bad_request = "HTTP/1.1 400 Bad Request\r\n\r\n";
send(conn, bad_request, strlen(bad_request), 0);
printf("Received malformed request, terminating connection.\n");
close(conn);
return -1;
}
return bytes_processed;
}
/**
* Sets up the connection state for a new socket connection.
*
* @param state A pointer to the connection_state structure to be initialized.
* @param sock The socket descriptor representing the new connection.
*
*/
static void connection_setup(struct connection_state *state, int sock) {
// Set the socket descriptor for the new connection in the connection_state
// structure.
state->sock = sock;
// Set the 'end' pointer of the state to the beginning of the buffer.
state->end = state->buffer;
// Clear the buffer by filling it with zeros to avoid any stale data.
memset(state->buffer, 0, HTTP_MAX_SIZE);
}
/**
* Discards the front of a buffer
*
* @param buffer A pointer to the buffer to be modified.
* @param discard The number of bytes to drop from the front of the buffer.
* @param keep The number of bytes that should be kept after the discarded
* bytes.
*
* @return Returns a pointer to the first unused byte in the buffer after the
* discard.
* @example buffer_discard(ABCDEF0000, 4, 2):
* ABCDEF0000 -> EFCDEF0000 -> EF00000000, returns pointer to first 0.
*/
char *buffer_discard(char *buffer, size_t discard, size_t keep) {
memmove(buffer, buffer + discard, keep);
memset(buffer + keep, 0, discard); // invalidate buffer
return buffer + keep;
}
/**
* Handles incoming connections and processes data received over the socket.
*
* @param state A pointer to the connection_state structure containing the
* connection state.
* @return Returns true if the connection and data processing were successful,
* false otherwise. If an error occurs while receiving data from the socket, the
* function exits the program.
*/
bool handle_connection(struct connection_state *state) {
// Calculate the pointer to the end of the buffer to avoid buffer overflow
const char *buffer_end = state->buffer + HTTP_MAX_SIZE;
// Check if an error occurred while receiving data from the socket
ssize_t bytes_read =
recv(state->sock, state->end, buffer_end - state->end, 0);
if (bytes_read == -1) {
perror("recv");
close(state->sock);
exit(EXIT_FAILURE);
} else if (bytes_read == 0) {
return false;
}
char *window_start = state->buffer;
char *window_end = state->end + bytes_read;
ssize_t bytes_processed = 0;
while ((bytes_processed = process_packet(state->sock, window_start,
window_end - window_start)) > 0) {
window_start += bytes_processed;
}
if (bytes_processed == -1) {
return false;
}
state->end = buffer_discard(state->buffer, window_start - state->buffer,
window_end - window_start);
return true;
}
/**
* Derives a sockaddr_in structure from the provided host and port information.
*
* @param host The host (IP address or hostname) to be resolved into a network
* address.
* @param port The port number to be converted into network byte order.
*
* @return A sockaddr_in structure representing the network address derived from
* the host and port.
*/
static struct sockaddr_in derive_sockaddr(const char *host, const char *port) {
struct addrinfo hints = {
.ai_family = AF_INET,
};
struct addrinfo *result_info;
// Resolve the host (IP address or hostname) into a list of possible
// addresses.
int returncode = getaddrinfo(host, port, &hints, &result_info);
if (returncode) {
fprintf(stderr, "Error parsing host/port");
exit(EXIT_FAILURE);
}
// Copy the sockaddr_in structure from the first address in the list
struct sockaddr_in result = *((struct sockaddr_in *)result_info->ai_addr);
// Free the allocated memory for the result_info
freeaddrinfo(result_info);
return result;
}
/**
* Sets up a TCP server socket and binds it to the provided sockaddr_in address.
*
* @param addr The sockaddr_in structure representing the IP address and port of
* the server.
*
* @return The file descriptor of the created TCP server socket.
*/
static int setup_server_socket(struct sockaddr_in addr) {
const int enable = 1;
const int backlog = 1;
// Create a socket
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// Avoid dead lock on connections that are dropped after poll returns but
// before accept is called
if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1) {
perror("fcntl");
exit(EXIT_FAILURE);
}
// Set the SO_REUSEADDR socket option to allow reuse of local addresses
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) ==
-1) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
// Bind socket to the provided address
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind");
close(sock);
exit(EXIT_FAILURE);
}
// Start listening on the socket with maximum backlog of 1 pending
// connection
if (listen(sock, backlog)) {
perror("listen");
exit(EXIT_FAILURE);
}
return sock;
}
static int setup_server_socket_udp(struct sockaddr_in addr){
struct protoent *proto = getprotobyname("UDP");
int sock = socket(AF_INET, SOCK_DGRAM, proto->p_proto);
if(sock == -1){
perror("Func: setup_server_socket_udp - socket returned with errors while creating an udp socket!");
exit(EXIT_FAILURE);
}
if(bind(sock, (struct sockaddr*) &addr, sizeof(addr)) == -1){
perror("Func: setup_server_socket_udp - bind returned with errors while binding socket to port!");
close(sock);
exit(EXIT_FAILURE);
}
return sock;
}
static void handle_udp_request(){
fprintf(stderr, "---%d---\n", _NODE_ID);
size_t received_bytes = 0;
lookup_request lr = {0};
struct sockaddr_storage caller_addr;
socklen_t addrlen = sizeof caller_addr;
if((received_bytes = recvfrom(server_socket_udp, &lr, sizeof(lookup_request), 0, (struct sockaddr *) &caller_addr, &addrlen)) == -1){
perror("Func: handle_udp_request - failed to receive data from caller!");
exit(EXIT_FAILURE);
}
perror("---HANDLE_UDP---\n");
// perror("[Serialized]\n");
// print_lookup_request(&lr);
extract_lookup_request(&lr);
perror("[Deserialized]\n");
print_lookup_request(&lr);
perror("----------------\n");
// DO LOOKUP
if (lr.message_type == 0)
{
// Check belonging
const int suc_id = _SUCC_ID;
in_addr_t suc_ip = htonl(inet_addr(_SUCC_IP));
struct in_addr suc_ip_s;
suc_ip_s.s_addr = suc_ip;
in_addr_t *callback_ip = &lr.node_ip.s_addr;
int callback_port = lr.node_port;
lookup_request backfire = {0};
const neighbor responsibility = check_neighborhood(lr.hash_id);
if (responsibility != res) {
// is succ responsible
if (responsibility == res_303)
{
lookup_request_init(&backfire, 1, suc_id, suc_ip, _SUCC_PORT, _NODE_ID);
}
else
{
clone_lookup_request(&backfire, &lr);
callback_ip = &suc_ip_s.s_addr;
callback_port = _SUCC_PORT;
}
}
call_network(&backfire, *callback_ip, callback_port);
}
elif (lr.message_type == 1)
{
lookup_request *toLookup = malloc(sizeof(lookup_request));
clone_lookup_request(toLookup, &lr);
push_lookup(toLookup);
perror("PUSHED ");
print_lookup_request(toLookup);
}
}
/**
* The program expects 3; otherwise, it returns EXIT_FAILURE.
*
* Call as:
*
* ./build/webserver self.ip self.port
*/
int main(int argc, char **argv) {
if (argc != 3 && argc != 4) {
return EXIT_FAILURE;
}
init_lookup_table();
/*
lookup_request toLookup1;
lookup_request_init(&toLookup1, 1, 65535, ntohl(inet_addr("127.0.0.1")), 4710, 1);
push_lookup(&toLookup1);
*/
if(argc == 3) _NODE_ID = 0;
elif(argc == 4) _NODE_ID = atoi(argv[3]);
// Set this DHT-Nodes ID
_NODE_PORT = atoi(argv[2]);
_NODE_IP = argv[1];
struct sockaddr_in addr = derive_sockaddr(argv[1], argv[2]);
// Set up a server socket.
int server_socket = setup_server_socket(addr);
server_socket_udp = setup_server_socket_udp(addr);
// Create an array of pollfd structures to monitor sockets.
struct pollfd sockets[3] = {
{.fd = server_socket, .events = POLLIN},
{.fd = server_socket_udp, .events = POLLIN}
};
struct connection_state state = {0};
while (true) {
// Use poll() to wait for events on the monitored sockets.
int ready = poll(sockets, sizeof(sockets) / sizeof(sockets[0]), -1);
if (ready == -1) {
perror("poll");
exit(EXIT_FAILURE);
}
// Process events on the monitored sockets.
for (size_t i = 0; i < sizeof(sockets) / sizeof(sockets[0]); i += 1) {
if (sockets[i].revents != POLLIN) {
// If there are no POLLIN events on the socket, continue to the
// next iteration.
continue;
}
int s = sockets[i].fd;
if (s == server_socket) {
// If the event is on the server_socket, accept a new connection
// from a client.
int connection = accept(server_socket, NULL, NULL);
if (connection == -1 && errno != EAGAIN && errno != EWOULDBLOCK) {
close(server_socket);
perror("accept");
exit(EXIT_FAILURE);
} else {
printf("Handling TCP request\n");
connection_setup(&state, connection);
// limit to one connection at a time
sockets[0].events = 0;
sockets[2].fd = connection;
sockets[2].events = POLLIN;
}
}
elif(s == server_socket_udp){
// DO UDP STUFF
printf("Handling UDP request\n");
handle_udp_request();
// sockets[1].events = 0;
}
else {
assert(s == state.sock);
// Call the 'handle_connection' function to process the incoming
// data on the socket.
bool cont = handle_connection(&state);
if (!cont) { // get ready for a new connection
sockets[0].events = POLLIN;
sockets[2].fd = -1;
sockets[2].events = 0;
}
}
}
}
free_lookup_table();
return EXIT_SUCCESS;
}