#include #include #include #include #include #include #include #include #include #include #include #include #include #include #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 atoi(getenv("PRED_ID")) #define _PRED_IP getenv("PRED_IP") #define _PRED_PORT atoi(getenv("PRED_PORT")) #define _SUCC_ID atoi(getenv("SUCC_ID")) #define _SUCC_IP getenv("SUCC_IP") #define _SUCC_PORT atoi(getenv("SUCC_PORT")) bool _DO_UDP = false; int _NODE_ID; const char *_NODE_IP; int _NODE_PORT; #define MAX_RESOURCES 100 typedef enum neighbor{ dunno = -1, not_res, res, res_303, }neighbor; struct tuple resources[MAX_RESOURCES] = { {"/static/foo", "Foo", sizeof "Foo" - 1}, {"/static/bar", "Bar", sizeof "Bar" - 1}, {"/static/baz", "Baz", sizeof "Baz" - 1}}; neighbor check_neighborhood(uint16_t); 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); elif(strstr(uri, static_)) uri_ptr += strlen(static_); elif(uri[0] == '/') uri_ptr++; return pseudo_hash((unsigned char *)uri_ptr, strlen(uri_ptr)); } /** * 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) { // 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); if (strcmp(request->method, "GET") == 0) { // Find the resource with the given URI in the 'resources' array. size_t resource_length; // const char *resource = get(request->uri, resources, MAX_RESOURCES, &resource_length); uint16_t resource_hash = hash_uri(request->uri); neighbor responsible = check_neighborhood(resource_hash); lookup_request *req = find_lookup(resource_hash); if (req != NULL) { if (req->message_type != 1) { printf("404\n"); reply = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"; offset = strlen(reply); } else { // TODO: Success 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); printf("303\n"); } } if (responsible == res) { sprintf(reply, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); offset = strlen(reply); printf("200\n"); } elif(responsible == res_303) { int suc_id = _SUCC_ID; if (resource_hash <= suc_id || suc_id >= 0 && suc_id < _NODE_ID) { printf("404\n"); reply = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"; offset = strlen(reply); } else { 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); printf("303\n"); } } elif(responsible == not_res) { sprintf(reply, "HTTP/1.1 503 Service Unavailable\r\nRetry-After: 1\r\nContent-Length: 0\r\n\r\n"); offset = strlen(reply); printf("503\n"); // TODO: Call other dht lookup_request lookreq; lookup_request_init(&lookreq, 0, _NODE_ID, inet_addr(_NODE_IP), _NODE_PORT, resource_hash); call_network(&lookreq, inet_addr(_SUCC_IP), _SUCC_PORT); } else { printf("404\n"); 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"; } 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"; } 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); } // Send the reply back to the client if (send(conn, reply, offset, 0) == -1) { perror("send"); close(conn); } } /** * 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. * */ size_t 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; } neighbor check_neighborhood(uint16_t hash) { int pre_id = _PRED_ID; int id = _NODE_ID; int suc_id = _SUCC_ID; if(pre_id == suc_id){ if(hash > id && hash <= suc_id) return res_303; return res; } // TODO: check correctness 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; } static void handle_udp_request(int _sock){ size_t received_bytes = 0; lookup_request lr = {0}; struct sockaddr_storage caller_addr; socklen_t addrlen = sizeof caller_addr; if((received_bytes = recvfrom(_sock, &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); } extract_lookup_request(&lr); printf("Received:\n\tMessage-type: %d\n\tlookup-hash: %hd\n", lr.message_type, lr.hash_id); // DO LOOKUP if (lr.message_type == 0) { // Check belonging const int suc_id = _SUCC_ID; in_addr_t suc_ip = 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}; if (lr.node_id == suc_id) { // Send back 404 not found clone_lookup_request(&backfire, &lr); backfire.message_type = -1; } else { const neighbor responsibility = check_neighborhood(lr.hash_id); if (responsibility == res) { lookup_request_init(&backfire, 1, _NODE_ID, inet_addr(_NODE_IP), _NODE_PORT, _PRED_ID); } elif (responsibility == not_res) { // is succ responsible if (lr.hash_id <= suc_id) { lookup_request_init(&backfire, 1, suc_id, suc_ip, _SUCC_PORT, _NODE_ID); } else { lookup_request_init(&backfire, 1, suc_id, suc_ip, _SUCC_PORT, _NODE_ID); 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); } else { // Message-Type: -1 } } /** * 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(); 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"); sockets[1].events = 0; handle_udp_request(s); } 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; }