summaryrefslogtreecommitdiffstats
path: root/hw1/proc_w.c
blob: 7b13ed2c5d414f473e216ff90c31d913e5d988ee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "common.h"
#include "proc.h"

#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

bool procconn(server* svr, request* requestP, int maxfd){
    int ret;

    struct sockaddr_in cliaddr;  // used by accept()
    int clilen;

    int conn_fd;  // fd for a new connection with client
    int file_fd;  // fd for file that we open for reading

    // TODO: Add IO multiplexing
    // Check new connection
    clilen = sizeof(cliaddr);
    conn_fd = accept(svr->listen_fd, (struct sockaddr*)&cliaddr, (socklen_t*)&clilen);
    if (conn_fd < 0) {
        if (errno == EINTR || errno == EAGAIN)
            return true;  // try again
        if (errno == ENFILE) {
            (void) fprintf(stderr, "out of file descriptor table ... (maxconn %d)\n", maxfd);
            return false;
        }
        e_err_exit("accept");
    }
    requestP[conn_fd].conn_fd = conn_fd;
    strcpy(requestP[conn_fd].host, inet_ntoa(cliaddr.sin_addr));
    fprintf(stderr, "getting a new request... fd %d from %s\n", conn_fd, requestP[conn_fd].host);

    file_fd = -1;

    do {
        ret = request_read(&requestP[conn_fd]);
        if (ret < 0) {
            fprintf(stderr, "bad request from %s\n", requestP[conn_fd].host);
            continue;
        }
        // requestP[conn_fd]->filename is guaranteed to be successfully set.
        if (file_fd == -1) {
            // open the file here.
            fprintf(stderr, "Opening file [%s]\n", requestP[conn_fd].filename);
            // TODO: Add lock
            // TODO: check if the request should be rejected.
            write(requestP[conn_fd].conn_fd, svr->accept_hdr, SVR_ACCEPT_HDR_LEN);
            file_fd = open(requestP[conn_fd].filename, O_WRONLY | O_CREAT | O_TRUNC,
                    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
        }
        if (ret == 0) break;
        write(file_fd, requestP[conn_fd].buf, requestP[conn_fd].buf_len);
    } while (ret > 0);
    fprintf(stderr, "Done writing file [%s]\n", requestP[conn_fd].filename);

    if (file_fd >= 0) close(file_fd);
    close(requestP[conn_fd].conn_fd);
    request_free(&requestP[conn_fd]);

    return true;
}