Implemented regex and directories

This commit is contained in:
Nate Choe
2022-01-22 21:20:57 -06:00
parent fbb3a4e8cd
commit be8e081cca
4 changed files with 69 additions and 21 deletions

View File

@@ -19,7 +19,9 @@
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <sys/stat.h>
#include <responses.h>
@@ -35,23 +37,51 @@ static int sendConnection(Connection *conn, char *format, ...) {
va_start(ap, format);
vsnprintf(data, len + 1, format, ap);
write(conn->fd, data, len);
if (write(conn->fd, data, len) < len) {
free(data);
return 1;
}
free(data);
return 0;
}
static void readResponse(Connection *conn, char *path) {
FILE *file = fopen(path, "r");
if (file == NULL) {
sendConnection(conn,
"HTTP/1.1 403 Forbidden\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Server: swebs/0.1\r\n"
"Content-Length: 21\r\n"
"\r\n"
"<h1>Invalid page</h1>\n"
);
FILE *file;
struct stat statbuf;
if (stat(path, &statbuf))
return;
if (S_ISDIR(statbuf.st_mode)) {
long reqPathLen = strlen(conn->path);
long pathLen = strlen(path);
char *assembledPath = malloc(reqPathLen + pathLen + 1);
if (assembledPath == NULL)
return;
memcpy(assembledPath, path, pathLen);
memcpy(assembledPath + pathLen, conn->path, reqPathLen + 1);
char requestPath[PATH_MAX];
if (realpath(assembledPath, requestPath) == NULL) {
free(assembledPath);
return;
}
char responsePath[PATH_MAX];
if (realpath(path, responsePath) == NULL) {
free(assembledPath);
return;
}
size_t responsePathLen = strlen(responsePath);
if (memcmp(requestPath, responsePath, responsePathLen)) {
free(assembledPath);
goto forbidden;
}
file = fopen(requestPath, "r");
free(assembledPath);
}
else
file = fopen(path, "r");
if (file == NULL) {
goto forbidden;
}
fseek(file, 0, SEEK_END);
long len = ftell(file);
@@ -59,7 +89,8 @@ static void readResponse(Connection *conn, char *path) {
if (data == NULL)
return;
fseek(file, 0, SEEK_SET);
fread(data, 1, len, file);
if (fread(data, 1, len, file) < len)
goto error;
fclose(file);
sendConnection(conn,
"HTTP/1.1 200 OK\r\n"
@@ -67,18 +98,33 @@ static void readResponse(Connection *conn, char *path) {
"Content-Length: %ld\r\n"
"\r\n", len
);
write(conn->fd, data, len);
if (write(conn->fd, data, len) < len)
goto error;
free(data);
fsync(conn->fd);
return;
error:
fclose(file);
return;
forbidden:
sendConnection(conn,
"HTTP/1.1 403 Forbidden\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Server: swebs/0.1\r\n"
"Content-Length: 21\r\n"
"\r\n"
"<h1>Invalid page</h1>\n"
);
return;
}
int sendResponse(Connection *conn, Sitefile *site) {
if (conn->path == NULL)
return 1;
puts(conn->path);
for (int i = 0; i < site->size; i++) {
if (site->content[i].respondto != conn->type)
continue;
if (strcmp(conn->path, site->content[i].path) == 0) {
if (regexec(&site->content[i].path, conn->path, 0, NULL, 0)
== 0) {
switch (site->content[i].command) {
case READ:
readResponse(conn, site->content[i].arg);