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.
93 lines
2.3 KiB
93 lines
2.3 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"
|
|
|
|
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) {
|
|
printf("Error: Failed to bind to %s:%d.\n", ADDR, PORT);
|
|
return 1;
|
|
}
|
|
|
|
if (listen(srvSocket, 10) < 0) {
|
|
printf("Error: Unable to listen on %s:%d.\n", ADDR, PORT);
|
|
return 1;
|
|
}
|
|
|
|
printf("Server (probably) listening on http://%s:%d\n", ADDR, PORT);
|
|
|
|
while(1) {
|
|
int client = accept(srvSocket, NULL, NULL);
|
|
ReqHeader request = readReqHeader(client);
|
|
char* tPath = request.path;
|
|
char* dot = strrchr(tPath, '.');
|
|
|
|
char *file = readFile(request.path);
|
|
ResHeader rawHeader;
|
|
rawHeader.protocol = request.protocol;
|
|
rawHeader.status = 200;
|
|
rawHeader.notice = "OK";
|
|
if (!dot || dot == tPath) { rawHeader.mime = "text/html"; } else {
|
|
/*switch (dot) {
|
|
"html":
|
|
rawHeader.mime = "text/html";
|
|
"css":
|
|
rawHeader.mime = "text/css";
|
|
"js":
|
|
rawHeader.mime = "text/javascript";
|
|
default:
|
|
rawHeader.mime = "text/plain";
|
|
}*/
|
|
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 {
|
|
rawHeader.mime = "text/plain";
|
|
}
|
|
}
|
|
if (errno == -1) {
|
|
rawHeader.status = 404;
|
|
rawHeader.notice = "Not Found";
|
|
} else if (errno > 0) {
|
|
rawHeader.status = 500;
|
|
rawHeader.notice = "Internal Server Error";
|
|
}
|
|
errno = 0;
|
|
printf("%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);
|
|
}
|
|
}
|