Make directories 404
parent
4c1ee7ed2c
commit
a9706cc6ac
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -3,6 +3,8 @@
|
|||
|
||||
#include <stdio.h>
|
||||
|
||||
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
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue