#include <stdio.h>
#include <sys/types.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>

int main(int argc, char** argv) {
    char* host_name = argv[1];
    char* path = argv[2];
    char* file_name = argv[3];


    struct addrinfo hints = {
            .ai_family = AF_INET,
            .ai_socktype = SOCK_STREAM
    };
    struct addrinfo* res = NULL;
    getaddrinfo(host_name, "http", &hints, &res);
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    connect(sock, res->ai_addr, res->ai_addrlen);
    char request[4096];
    struct stat info;
    stat(file_name, &info);
    snprintf(request, sizeof(request),
             "POST %s HTTP/1.1\r\n"
             "Content-Length: %ld\r\n"
             "Host: %s\r\n"
             "Connection: close\r\n"
             "\r\n",
             path, info.st_size, host_name);
    write(sock, request, strnlen(request, sizeof(request)));
    int fd = open(file_name, O_RDONLY);
    char buf[4096];
    int readed = 0;
    while (0 < (readed = read(fd, buf, sizeof(buf)))) {
        write(sock, buf, readed);
    }
    close(fd);

    FILE* in = fdopen(sock, "r");
    char headers = 0;
    while (fgets(buf, sizeof(buf), in)) {
        if (0 == strcmp(buf, "\n") || 0 == strcmp(buf, "\r\n")) {
            headers = 1;
        }
        if (headers) {
            printf("%s\n", buf);
        }
    }
    fclose(in);
    close(sock);
}