aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorverdant <im@verdant.ee>2026-06-09 18:13:09 +0800
committerverdant <im@verdant.ee>2026-06-09 18:13:09 +0800
commitd1e255ad5eeb6768b3125bdc4e8fb1ab1e49f21a (patch)
tree71c918e2f961ff9f5250dd3b5b6ed9185134b0a8
parent4a03cd3caeb21442717e5b1bf7fb482ea4d37c70 (diff)
downloadshsd-d1e255ad5eeb6768b3125bdc4e8fb1ab1e49f21a.tar.gz
shsd-d1e255ad5eeb6768b3125bdc4e8fb1ab1e49f21a.zip
Check if the file exists before send, or send a 404 file
-rw-r--r--server.c52
1 files changed, 52 insertions, 0 deletions
diff --git a/server.c b/server.c
index 15f8a88..53368e9 100644
--- a/server.c
+++ b/server.c
@@ -11,6 +11,8 @@
#include <sys/sendfile.h>
#include <unistd.h>
+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;
}