Skip to content
Snippets Groups Projects
Select Git revision
  • 9e8a15634f2ada06bae99978079bcdec4603dc88
  • master default protected
  • find_previous_work
3 results

4_accepted.html

Blame
  • http-server.c 10.50 KiB
    /*
    ** http-server.c
    */
    
    #include <errno.h>
    #include <stdbool.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <assert.h>
    
    #include <arpa/inet.h>
    #include <fcntl.h>
    #include <netdb.h>
    #include <netinet/in.h>
    #include <strings.h>
    #include <sys/select.h>
    #include <sys/sendfile.h>
    #include <sys/socket.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include "http-parser.h"
    #include "http-response.h"
    #include "user.h"
    
    // constants
    static char const * const HTTP_200_FORMAT = "HTTP/1.1 200 OK\r\n\
    Content-Type: text/html\r\n\
    Content-Length: %ld\r\n\r\n";
    static char const * const HTTP_400 = "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n";
    static int const HTTP_400_LENGTH = 47;
    static char const * const HTTP_404 = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
    static int const HTTP_404_LENGTH = 45;
    
    
    bool player_session(char* buff, int sockfd, char* file_name, char* response){
        // get the size of the file
        printf("runnning player session functin\n");
        struct stat st;
        stat(file_name, &st);
        int n = sprintf(buff, response, st.st_size);
        // send the header first
        printf("sending header\n");
        if (write(sockfd, buff, n) < 0)
        {
            perror("write");
            return false;
        }
        // send the file
        printf("sending file\n");
        int filefd = open(file_name, O_RDONLY);
        do
        {
            n = sendfile(sockfd, filefd, NULL, 2048);
        }
        while (n > 0);
        if (n < 0)
        {
            perror("sendfile");
            close(filefd);
            return false;
        }
        printf("about to close");
        close(filefd);
        return true;
    }
    bool get_request(char* buff, int sockfd, char* file_name){
        // get the size of the file
        struct stat st;