From 1a406503713a3763fa88109a60b9ca03593b111c Mon Sep 17 00:00:00 2001 From: Matt Strapp Date: Sun, 6 Dec 2020 17:12:22 -0600 Subject: oops --- P4/util.c | 113 +++++++++++++++++++++++++++++++++++++++++++++++++++--- P4/web_server_sol | Bin 2 files changed, 108 insertions(+), 5 deletions(-) mode change 100644 => 100755 P4/web_server_sol diff --git a/P4/util.c b/P4/util.c index 77342c8..f9b8d1b 100644 --- a/P4/util.c +++ b/P4/util.c @@ -15,8 +15,8 @@ #include #include "util.h" -//Global socket for all things -int sock; +//Global socket +int sockfd, new_socket; /********************************************** * init @@ -29,26 +29,32 @@ int sock; - if init encounters any errors, it will call exit(). ************************************************/ void init(int port) { - if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == -1) { + if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) { perror("Cannot create socket"); exit(EXIT_FAILURE); } //Socket describer struct sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(port); //Allow port to be released int enable = 1; - if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&enable, sizeof(int)) == -1) { + if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&enable, sizeof(int)) == -1) { perror("Cannot set socket option"); exit(EXIT_FAILURE); } //Bind socket and open the port - if (bind(sock, (struct sockaddr*) &addr, sizeof(addr)) == -1) { + if (bind(sockfd, (struct sockaddr*) &addr, sizeof(addr)) == -1) { perror("Cannot bind socket"); exit(EXIT_FAILURE); } + //Enable listen + if (listen(sockfd, 20) == -1) { + perror("Cannot set listen queue"); + exit(EXIT_FAILURE); + } } /********************************************** @@ -59,6 +65,15 @@ void init(int port) { - if the return value is negative, the request should be ignored. ***********************************************/ int accept_connection(void) { + + struct sockaddr_in address; + int addrlen = sizeof(address); + if ((new_socket = accept(sockfd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { + perror("Accept"); + return -1; + } + return(new_socket); + } /********************************************** @@ -77,6 +92,31 @@ int accept_connection(void) { specific 'connection'. ************************************************/ int get_request(int fd, char *filename) { + + char buffer[2048] = "\0"; + char get[100], http[100]; + + read(fd, buffer, 2048); + + if(sscanf(buffer, "%s %s %s", get, filename, http) < 2) { // Read HTTP Get request and parse + close(fd); + return -1; + } + else if (strcmp(get, "GET")) { + close(fd); + return -2; + } + else if (strlen(filename) > 1023) { + close(fd); + return -3; + } + for (int i=0; i