From d1e255ad5eeb6768b3125bdc4e8fb1ab1e49f21a Mon Sep 17 00:00:00 2001 From: verdant Date: Tue, 9 Jun 2026 18:13:09 +0800 Subject: Check if the file exists before send, or send a 404 file --- server.c | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/server.c b/server.c index 15f8a88..53368e9 100644 --- a/server.c +++ b/server.c @@ -11,6 +11,8 @@ #include #include +typedef enum { GET = 0, POST = 1, UNKNOWN = -1 } HTTP_METHODS; + int shsd_sendfile(int in_fd, FILE *ou_fd) { struct stat s; @@ -24,6 +26,56 @@ int shsd_sendfile(int in_fd, FILE *ou_fd) return 0; } +HTTP_METHODS get_require_method(char *method) +{ + HTTP_METHODS m; + if (strcmp(method, "GET") == 0) { + return m = GET; + } + + if (strcmp(method, "POST") == 0) { + return m = POST; + } + + else { + return m = UNKNOWN; + } +} + +int check_file_stat(const char *path, int fd) +{ + struct stat st; + if (stat(path, &st) == -1 && S_ISDIR(st.st_mode)) { + return -1; + } + + return 0; +} + +int handle_client(int client_fd, char *buf) +{ + char method[16], path[256]; + if (sscanf(buf, "%15s %255s", method, path) < 2) { + close(client_fd); + return -1; + } + + if (strcmp(path, "/") == 0) { + strcpy(path, "/index.html"); + } + + char local_path[1024]; + snprintf(local_path, sizeof(local_path), "./www%s", path); + + FILE *fp = fopen(local_path, "r"); + if (!fp) { + perror("fopen"); + fp = fopen("./www/404.html", "r"); + shsd_sendfile(client_fd, fp); + return -1; + } + shsd_sendfile(client_fd, fp); + return 0; } -- cgit v1.2.3