From 766c3abd4d690ae9e212318d815c5209300b8f0c Mon Sep 17 00:00:00 2001
From: Not Zed <notzed@gmail.com>
Date: Thu, 11 Jul 2024 19:20:09 +0930
Subject: [PATCH] Pass the url from the request through the url decoder. Add
 some debug to print remote ip addr.

---
 ez-http.c | 23 +++++++++++++++++++++--
 ez-http.h |  1 +
 2 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/ez-http.c b/ez-http.c
index f0a36ac..b804f27 100644
--- a/ez-http.c
+++ b/ez-http.c
@@ -25,6 +25,7 @@
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
+#include <arpa/inet.h>
 #include <ctype.h>
 #include <sys/uio.h>
 #include <netdb.h>
@@ -283,6 +284,8 @@ static int parse_request_status(struct ez_httprequest *r) {
 	} else
 		return -1;
 
+	url_decode(url);
+
 	r->method = r->http.status;
 	r->url = url;
 	r->version = version;
@@ -510,6 +513,17 @@ int httpserver_run(struct ez_httpserver *s) {
 			setsockopt(conn.fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
 		}
 
+		char ipstr[INET6_ADDRSTRLEN];
+
+		// deal with both IPv4 and IPv6:
+		if (conn.addr.sin_family == AF_INET) {
+			struct sockaddr_in *s = (struct sockaddr_in *)&conn.addr;
+			inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr));
+		} else { // AF_INET6
+			struct sockaddr_in6 *s = (struct sockaddr_in6 *)&conn.addr;
+			inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof(ipstr));
+		}
+
 		// Default response
 		init_response(&rep, &conn);
 		rep.code = 500;
@@ -520,6 +534,8 @@ int httpserver_run(struct ez_httpserver *s) {
 		res = read_http(&req.http);
 
 		if (res == 0) {
+			if (s->debug > 0)
+				printf("%-15s \"%s\"\n", ipstr, req.http.status);
 			res = parse_request_status(&req);
 			if (res == 0) {
 				const struct ez_httphandler key = { .path = req.url };
@@ -532,9 +548,12 @@ int httpserver_run(struct ez_httpserver *s) {
 				if (handler && handler->mode == EZ_PATH_PREFIX && strncmp(req.url, handler->path, strlen(handler->path)) != 0)
 					handler = NULL;
 
-				if (handler)
+				if (handler) {
+					if (s->debug > 0)
+						printf("%s %s\n", req.method, req.url);
+
 					quit = handler->fn(&req, &rep);
-				else
+				} else
 					httpresponse_set_response(&rep, 404, "Missing");
 			} else
 				httpresponse_set_response(&rep, 400, "Invalid");
diff --git a/ez-http.h b/ez-http.h
index b936d89..d2417fb 100644
--- a/ez-http.h
+++ b/ez-http.h
@@ -121,6 +121,7 @@ void httpresponse_set_response(struct ez_httpresponse *r, int code, const char *
  */
 struct ez_httpserver {
 	ez_tree handlers;	// tree of struct ez_httphandler
+	int debug;
 
 	struct sockaddr_in addr;
 	int fd;
-- 
2.39.5