64 lines
2.1 KiB
C
64 lines
2.1 KiB
C
#include "http_server.h"
|
|
#include "../common/socket_helper.h"
|
|
#include "socket_server.h"
|
|
#include <errno.h>
|
|
#include <stdbool.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/signal.h>
|
|
#include <sys/socket.h>
|
|
#include <unistd.h>
|
|
|
|
bool running = true;
|
|
|
|
void handle_signal(int signal) {
|
|
if (signal == SIGPIPE) {
|
|
// We must ignore SIGPIPEs such that EPIPEs can be returned from socket read/write functions.
|
|
return;
|
|
}
|
|
if (signal == SIGINT || signal == SIGTERM) {
|
|
running = false;
|
|
}
|
|
}
|
|
|
|
int main(int argc, char* argv[]) {
|
|
if (argc != 2) {
|
|
printf("%s\n", USAGE_STRING);
|
|
return 1;
|
|
}
|
|
char *port = argv[1];
|
|
long port_num = strtol(port, NULL, 10);
|
|
if (port_num < MIN_PORT || port_num > MAX_PORT || errno == ERANGE || errno == EINVAL) {
|
|
printf("%s\n", PORT_ERROR);
|
|
return 1;
|
|
}
|
|
struct sigaction sa = {.sa_handler = &handle_signal, .sa_flags = 0};
|
|
sigemptyset(&sa.sa_mask);
|
|
sigaction(SIGINT, &sa, NULL);
|
|
sigaction(SIGTERM, &sa, NULL);
|
|
sigaction(SIGPIPE, &sa, NULL);
|
|
|
|
struct server_info info = setup(port_num);
|
|
if (info.status == STATUS_ERROR) {
|
|
printf("%s\n", strerror(errno));
|
|
return 1;
|
|
}
|
|
while (running) {
|
|
enum socket_result serve_result = serve_one_request(info.sock_fd);
|
|
if (serve_result != RESULT_OK && errno != EINTR) {
|
|
printf("Got error code %d when serving a request.\n", serve_result);
|
|
if (serve_result == RESULT_MALFORMED) {
|
|
printf("\tMalformed request. This may be due to the client closing the socket prematurely.\n");
|
|
} else if (serve_result == RESULT_READ_ERROR) {
|
|
printf("\tThere was an error reading from the socket.\n");
|
|
} else if (serve_result == RESULT_PROCESSING_ERROR) {
|
|
printf("\tThere was an error while processing the data from the socket. This may be due to a malformed request.\n");
|
|
} else if (serve_result == RESULT_WRITE_ERROR) {
|
|
printf("\tThere was an error writing to the socket.\n");
|
|
}
|
|
}
|
|
}
|
|
close(info.sock_fd);
|
|
}
|