You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.5 KiB

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include "resHeader.h"
#include "reqHeader.h"
#include "file.h"
#include "log.h"
int srv(char* ADDR, int PORT) {
char buffer[BUFSIZ];
int srvSocket;
struct sockaddr_in srvAddr;
srvSocket = socket(AF_INET, SOCK_STREAM, 0);
srvAddr.sin_family = AF_INET;
srvAddr.sin_port = htons(PORT);
srvAddr.sin_addr.s_addr = inet_addr(ADDR);
if (bind(
srvSocket,
(struct sockaddr*) &srvAddr,
sizeof(srvAddr)
) < 0) {
error("Failed to bind to %s:%d.\n", ADDR, PORT);
return 1;
}
if (listen(srvSocket, 10) < 0) {
error("Unable to listen on %s:%d.\n", ADDR, PORT);
return 1;
}
info("Server (probably) listening on http://%s:%d\n", ADDR, PORT);
while(1) {
int hasTriedIndex;
int client = accept(srvSocket, NULL, NULL);
ReqHeader request = readReqHeader(client);
funy: {
char* dot = strrchr(request.path, '.');
char *file = readFile(request.path);
ResHeader rawHeader;
rawHeader.protocol = request.protocol;
rawHeader.status = 200;
rawHeader.notice = "OK";
if (!dot || dot == request.path) {
if (!hasTriedIndex) {
strcat(request.path, "/index.html");
info("trying to upgrade directory to index.html\n");
hasTriedIndex = 1;
goto funy;
} else {
warn("file extension does not exist or is the same as request path\n");
hasTriedIndex = 1;
rawHeader.mime = "text/plain";
}
} else {
if (!strcmp(dot, ".html")) {
rawHeader.mime = "text/html";
} else if (!strcmp(dot, ".css")) {
rawHeader.mime = "text/css";
} else if (!strcmp(dot, ".ico")) {
rawHeader.mime = "image/vnd.microsoft.icon";
} else if (!strcmp(dot, ".js")) {
rawHeader.mime = "text/javascript";
} else {
warn("mimetype for %s not found\n", request.path);
rawHeader.mime = "text/plain";
}
if (hasTriedIndex == 1) {
hasTriedIndex = 2;
} else {
hasTriedIndex = 0;
}
}
if (errno == -1) {
rawHeader.status = 404;
rawHeader.notice = "Not Found";
} else if (errno > 0 && !(hasTriedIndex == 2)) {
rawHeader.status = 500;
rawHeader.notice = "Internal Server Error";
}
errno = 0;
hasTriedIndex = 0;
reqlog("%d %s\n", rawHeader.status, request.path);
char tmpHeader[1024];
makeHeader(tmpHeader, &rawHeader);
char resHeader[1024]; //= "HTTP/1.1 200 OK\r\n\nHello, world!";
sprintf(resHeader, "%s%s", (char*)tmpHeader, file);
send(client, resHeader, strlen(resHeader), 0);
close(client);
}
}
}