sneedmc.org/main.c
sneedium 8990aed644
Updated website to reflect new packaging and git.
Signed-off-by: sneedium <sneed@sneedmc.org>
2022-11-06 16:50:31 -05:00

111 lines
3.2 KiB
C

#include "mongoose.h"
#include "index.h"
#include "css.h"
// sneed in phone number, backwards
char *port = "33367";
void trim(char *str) {
char *_str = str;
int len = strlen(_str);
while(*_str && *_str == '/') ++_str, --len;
memmove(str, _str, len + 1);
}
bool eq(const char *src, const char *comp, size_t len) {
return (strncmp(src, comp, len) == 0);
}
void redir(struct mg_connection *nc, char *to) {
char *loc = malloc(strlen(to) + 14);
sprintf(loc, "Location: %s\r\n", to);
mg_http_reply(nc, 302, loc, to);
}
static void ev_handler(struct mg_connection *nc, int ev, void *p, void *f) {
if (ev == MG_EV_HTTP_MSG) {
struct mg_http_message *hm = (struct mg_http_message *) p;
char *uri = malloc(hm->uri.len + 1);
snprintf(uri, hm->uri.len + 1, "%s", hm->uri.ptr);
trim(uri);
char *query = NULL;
struct mg_str hquery = hm->query;
if (hquery.len > 0) {
char *base_query = malloc(hquery.len + 1);
snprintf(base_query, hquery.len + 1, "%s", hquery.ptr);
query = malloc(256);
mg_url_decode(base_query, hquery.len + 1, query, 256, 0);
free(base_query);
} else {
query = malloc(1);
sprintf(query, "");
}
struct mg_str *pmhost = mg_http_get_header(hm, "Host");
struct mg_str mhost;
if (pmhost == NULL) {
fprintf(stderr, "request sent with no Host header");
mhost = mg_str("<UNKNOWN DOMAIN>");
} else {
mhost = *pmhost;
}
char *host = malloc(mhost.len + 1);
snprintf(host, mhost.len + 1, "%s", mhost.ptr);
char *body = strdup(hm->body.ptr);
if (strncmp(hm->method.ptr, "POST", hm->method.len) == 0) {
} else if (strncmp(hm->method.ptr, "GET", hm->method.len) == 0){
if (eq(uri, "", 1) || eq(uri, "index.html", 11)) {
// allow for dynamic stuff in the future
mg_http_reply(nc, 200, "", INDEX_HTML, BASIC_STYLE);
} else if (eq(uri, "src", 4)) {
redir(nc, "https://git.sneedmc.org/Sneederix/sneedmc.org");
} else if (eq(uri, "git", 4)) {
redir(nc, "https://git.sneedmc.org/Sneederix/sneedmc");
} else if (eq(uri, "build", 6)) {
redir(nc, "https://git.sneedmc.org/Sneederix/sneedmc/src/branch/develop/BUILD.md");
} else {
struct mg_http_serve_opts opts = {.root_dir = "."}; // Serve local dir
mg_http_serve_dir(nc, p, &opts);
}
} else {
mg_http_reply(nc, 405, "Allow: GET, POST\r\n", "");
}
free(uri);
free(host);
free(body);
free(query);
}
}
int main(int argc, char *argv[]) {
struct mg_mgr mgr;
struct mg_connection *nc;
mg_mgr_init(&mgr);
printf("Starting web server on port %s\n", port);
char *str_port = malloc(20);
sprintf(str_port, "http://0.0.0.0:%s", port);
nc = mg_http_listen(&mgr, str_port, ev_handler, &mgr);
if (nc == NULL) {
printf("Failed to create listener\n");
return 1;
}
for (;;) { mg_mgr_poll(&mgr, 1000); }
mg_mgr_free(&mgr);
return 0;
}