Initial commit

This commit is contained in:
Pin
2022-01-29 18:12:15 -05:00
commit 7ddfb06557
6 changed files with 177 additions and 0 deletions

98
cmd/server.c Normal file
View File

@@ -0,0 +1,98 @@
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
// Local Includes
#include "httpStruct.h"
#include "socketHelp.h"
#define PORT 8080
int parseHTTPRequest(char buffer[], struct HTTPRequest *r) {
char temp[1];
char *token;
int line = 0;
char * checkLine;
checkLine = malloc(1000);
for (int i = 0; i < strlen(buffer); i++) {
temp[0] = buffer[i];
if ((!strcmp(temp, "\n")) && (i != 0)) {
// Config Check
if (line == 0) {
token = strtok(checkLine, " ");
// HTTP Request Type
if (!strcmp(token, "GET")) {
r->requestType = malloc(strlen(token));
strcpy(r->requestType, token);
}
} else {
token = strtok(checkLine, ":");
// Host Check
if (!strcmp(token, "Host")) {
token = strtok(NULL, "");
r->requestHost = malloc(strlen(token));
strcpy(r->requestHost, token);
}
// Reset checkline
}
if (strlen(checkLine) > 0) {
// Clear checkLine
memset(checkLine,0,strlen(checkLine));
}
line++;
} else {
strcat(checkLine, temp);
}
}
free(checkLine);
return 0;
}
int returnRequest(int socket) {
char *hello = "HTTP/1.1 200 OK\nContent-Length: 5\nConnection: close\n\nhello\n\n";
printf("Returning\n%s", hello);
send(socket, hello, strlen(hello), 0);
return 0;
}
int handleRequest(char buffer[], int socket) {
struct HTTPRequest r;
// Grabbing relevant information out of request
parseHTTPRequest(buffer, &r);
returnRequest(socket);
return 0;
}
int main(int argc, char const *argv[]) {
struct sockaddr_in address;
int server_fd, new_socket;
int checkerr = 0;
int addrlen = sizeof(address);
char buffer[1024] = {};
checkerr = createSocket(PORT, &server_fd, &address, &addrlen);
if (checkerr != 0) {
perror("Error creating socket");
exit(EXIT_FAILURE);
}
// Handle incoming requests
while(1) {
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t *)&addrlen))<0) {
perror("Accept connection error");
exit(EXIT_FAILURE);
}
read(new_socket, buffer, 1024);
printf("Conn received:\n%s\n", buffer);
handleRequest(buffer, new_socket);
}
exit(EXIT_SUCCESS);
}