diff --git a/server/request_handling.c b/server/request_handling.c index b9925a2..6b3e909 100644 --- a/server/request_handling.c +++ b/server/request_handling.c @@ -106,29 +106,32 @@ void free_request_line_items(struct request_line *parsed_line) { * * @return -1 For an I/O error, 0 if successful. */ -int get_file_from_uri(const char *uri, struct requested_file *req_file) { +enum file_result get_file_from_uri(const char *uri, struct requested_file *req_file) { const char *resource = uri; if (strcmp(uri, "/") == 0) { resource = "TMDG.html"; } else if (*uri == '/') { // If our uri starts with a slash, we can ignore it. - uri++; + resource++; } struct stat file_stat; int stat_result = stat(resource, &file_stat); if (stat_result == -1) { - return -1; + return RESULT_IO_ERROR; + } + if (S_ISDIR(file_stat.st_mode)) { + return RESULT_NOT_FILE; } FILE *open_file = fopen(resource, "r"); if (open_file == NULL) { - return -1; + return RESULT_IO_ERROR; } rewind(open_file); req_file->size = file_stat.st_size; req_file->file = open_file; - return 0; + return RESULT_FILE_OK; } diff --git a/server/request_handling.h b/server/request_handling.h index b2d5cb6..7eace14 100644 --- a/server/request_handling.h +++ b/server/request_handling.h @@ -3,6 +3,8 @@ #include +enum file_result{RESULT_IO_ERROR, RESULT_NOT_FILE, RESULT_FILE_OK}; + struct request_line { char *http_version; char *method; @@ -16,6 +18,6 @@ struct requested_file { int parse_request_line(const char *line, struct request_line *parsed_line); void free_request_line_items(struct request_line *parsed_line); -int get_file_from_uri(const char *uri, struct requested_file *req_file); +enum file_result get_file_from_uri(const char *uri, struct requested_file *req_file); #endif diff --git a/server/socket_server.c b/server/socket_server.c index 5a016a1..bb8adc6 100644 --- a/server/socket_server.c +++ b/server/socket_server.c @@ -247,11 +247,11 @@ enum socket_result serve_one_request(int sock_fd) { // Attempt to read the file and return it. struct requested_file file = {}; int file_result = get_file_from_uri(parsed_request_line.uri, &file); - if (file_result == -1) { + if (file_result != RESULT_FILE_OK) { int send_result = 0; - if (errno == ENOENT) { + if (file_result == RESULT_NOT_FILE || (file_result == RESULT_IO_ERROR && errno == ENOENT)) { send_result = send_headers(404, client_fd, -1); - } else if (errno == EACCES) { + } else if (file_result == RESULT_IO_ERROR && errno == EACCES) { send_result = send_headers(403, client_fd, -1); } else { free_request_line_items(&parsed_request_line); @@ -275,7 +275,7 @@ enum socket_result serve_one_request(int sock_fd) { } free_request_line_items(&parsed_request_line); free_request_items(message); - if (file_result != -1) { + if (file_result == RESULT_FILE_OK) { fclose(file.file); }