BarryServer : Git

All the code for all my projects
// BarryServer : Git / IRCWebHooks / commit / c7c09b09808cac46441f41e3424797ff52e17005 / src / webserver.c

// Related

IRCWebHooks

Barry Adding HTTP authentication to webserver c7c09b0 (3 years, 3 months ago)
diff --git a/src/webserver.c b/src/webserver.c
index 60ad2e5..4f7b4cd 100644
--- a/src/webserver.c
+++ b/src/webserver.c
@@ -5,6 +5,7 @@
 #include <arpa/inet.h>
 #include <openssl/ssl.h>
 #include <openssl/err.h>
+#include <b64/cdecode.h>
 
 #include "config.h"
 #include "list.h"
@@ -109,8 +110,6 @@ srv(int argc, char **argv)
 #ifdef SSL_SERVER
 		SSL *ssl;
 #endif
-		const char reply[] = "test\r\n";
-
 		int client = accept(sock, (struct sockaddr*)&addr, &len);
 		if (client < 0) {
 			perror("Unable to accept");
@@ -125,8 +124,9 @@ srv(int argc, char **argv)
 
 		char buf[1025];
 		char *p, *uri, *cont;
-		int conlen;
-		char key[64];
+		int conlen, i;
+		char key[64], *dkey;
+		char httpResponse[4];
 
 #ifdef SSL_SERVER
 		SSL_read(ssl, &buf, 1024);
@@ -141,6 +141,30 @@ srv(int argc, char **argv)
 			cont = uri + strlen(uri) + 1;
 			if ((p = strstr(cont, "Content-Length: ")) != NULL) {
 				sscanf(p+16, "%i", &conlen);
+			} else {
+				strcpy(httpResponse, "411");
+				goto ignore;
+			}
+			if ((p = strstr(cont, "Authorization: Basic ")) != NULL) {
+				p += 21;
+				for (i = 0; *p != '\r'; i++)
+					key[i] = *p++;
+				key[i] = '\0';
+
+				dkey = malloc(64);
+				p = dkey;
+				base64_decodestate s;
+				base64_init_decodestate(&s);
+				p += base64_decode_block(key, strlen(key), p, &s);
+				*p = '\0';
+
+				if (strcmp(dkey, WEB_AUTH)) {
+					strcpy(httpResponse, "401");
+					goto ignore;
+				}
+			} else {
+				strcpy(httpResponse, "401");
+				goto ignore;
 			}
 			if ((p = strstr(cont, "content=")) != NULL) {
 				p[conlen] = '\0';
@@ -157,15 +181,20 @@ srv(int argc, char **argv)
 					raw("PRIVMSG #%s :%s\r\n", buf+6, p);
 				}
 			}
+ignore:
 			memset(&buf, 0, 1024);
 		}
 
 #ifdef SSL_SERVER
-		SSL_write(ssl, "HTTP/1.1 200 OK\r\n", 17);
+		SSL_write(ssl, "HTTP/1.1 ", 9);
+		SSL_write(ssl, httpResponse, strlen(httpResponse));
+		SSL_write(ssl, " OK\r\n", 5);
 		SSL_shutdown(ssl);
 		SSL_free(ssl);
 #else
-		write(client, "HTTP/1.1 200 OK\r\n", 17);
+		write(client, "HTTP/1.1 ", 9);
+		write(client, httpResponse, strlen(httpResponse));
+		write(client, " OK\r\n", 5);
 #endif
 		close(client);
 	}