summaryrefslogtreecommitdiff
path: root/Year_3/TSDWL/webserver/server.c
blob: 000c66fcc89fcae1b2c3e9cd3b08659771af34eb (plain)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/* An example of the work of this file is showed at [1]
 *
 * [1] https://it.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Richiesta_GET_e_risposta_di_successo
 */
#include <arpa/inet.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#define DEFAULT_WWW "./www"

typedef enum {
    GET,
    /* TODO: types below */
    HEAD,
    OPTIONS,
    POST,
    PUT,
    PATCH,
    DELETE
} methods;

typedef enum {
    /* Some of the HTTP versions defined at [1]
     *
     * [1] https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#History
     */
    HTTP1, /* HTTP/1.0 */
    HTTP1_1, /* HTTP/1.1 */
    HTTP2, /* HTTP/2   */
} http_t;

char*
http_text(http_t version)
{
    char* map[] = {
        "HTTP/1.0",
        "HTTP/1.1",
        "HTTP/2"
    };

    return map[version];
}

typedef enum {
    /* Get some responses names from [1]
     *
     * [1] https://www.django-rest-framework.org/api-guide/status-codes/#successful-2xx
     */
    HTTP_200_OK,
    HTTP_206_PARTIAL_CONTENT,
    HTTP_400_BAD_REQUEST,
    HTTP_404_NOT_FOUND,
    HTTP_405_METHOD_NOT_ALLOWED
    /* TODO: Include more and more responses */
} response_t;

char*
response_text(response_t response)
{
    char* map[] = {
        "200 OK",
        "206 PARTIAL CONTENT",
        "400 BAD REQUEST",
        "404 NOT FOUND",
        "405 METHOD NOT ALLOWED"
    };

    return map[response];
}

typedef struct {
    methods method;
    char path[256]; /* FIXME: handle path with more than 256 chars */
    http_t http_version;
} request_t;

/* TODO: Make the parsing of headers */
void
read_headers(int* fd, char** headers, int* headers_num)
{
    char ch;
    int flag_read; /* Used to check the return value of `read` function */
    unsigned i;
    char buffer[1024];

    *headers_num = 0;

    while (*headers_num < 24) {
        i = 0;

        buffer[0] = '\0';
        headers[*headers_num] = malloc(sizeof(char) * 1024);
        while ((flag_read = read(*fd, &ch, 1)) != 0) {
            if (flag_read == -1) {
                perror("Error reading the headers");
                exit(1);
            }

            buffer[i] = ch;
            if (ch == '\n' && (i < 1 || buffer[i - 1] == '\r')) {
                break;
            }

            i++;
        }

        buffer[i - 1] = '\0';
        if (i < 2) {
            break;
        }

        memcpy(headers[*headers_num], buffer, i);
        (*headers_num)++;
    }
}

void
get_client_ip(int fd, char* buffer)
{
    struct sockaddr_in addr;
    socklen_t addr_size = sizeof(struct sockaddr_in);
    getpeername(fd, (struct sockaddr*)&addr, &addr_size);
    strcpy(buffer, inet_ntoa(addr.sin_addr));
}

int
parse_first_line(request_t* request, const char* header, size_t len)
{
    char* token;
    char line[255];
    int i;

    i = 0;
    strcpy(line, header);
    token = strtok(line, " ");
    do {
        switch (i) {
        case 0: {
            if (strcmp(token, "GET") == 0) {
                request->method = GET;
            } else {
                fprintf(stderr, "'%s' method not supported\n", token);
                goto parse_error;
            }
            /* TODO: Handle the other HTTP methods */
            break;
        }
        case 1: {
            if (token[0] != '/') {
                fprintf(stderr, "'%s' must starts with a '/'\n", token);
                goto parse_error;
            }
            strcpy(request->path, token);
            break;
        }
        case 2: {
            if (strcmp(token, "HTTP/1.0") == 0) {
                request->http_version = HTTP1;
            } else if (strcmp(token, "HTTP/1.1") == 0) {
                request->http_version = HTTP1_1;
            } else if (strcmp(token, "HTTP/2") == 0) {
                request->http_version = HTTP2;
            } else {
                fprintf(stderr, "'%s' version not supported\n", token);
                goto parse_error;
            }
            break;
        }
        /* If it comes here, it means that the header has more than 3 tokens */
        default: {
            fprintf(stderr, "Header does not have a valid syntax\n");
            goto parse_error;
        }
        }

        i++;
        token = strtok(NULL, " ");
    } while (token != NULL);

    return 0;

parse_error:
    return -1;
}

void
read_file(char* root, request_t* request, int client)
{
    /* FIXME: In Linux the max name length is 255, but here we include the 
     * root, and I don't want to use an array of 511 bytes (255*2+1). So I am
     * supposing a max path of 300 chars. */
    char path[300];
    char buffer[1024];
    int n;
    int fd;
    int root_len;
    int file_len;
    char* file;
    response_t response;
    int is_partial_file;
    time_t now;
    struct stat sb;

    /* Copy the path because we shouldn't edit the variable on the stack */
    file = request->path;
    root_len = strlen(root);
    file_len = strlen(file);

    if (root[0] == '.' && root[1] == '/') {
        root += 2;
        root_len -= 2;
    }

    if (root[root_len - 1] == '/') {
        root_len--;
    }

    /* Considers this kind of path like `/index.html` */
    if (file_len == 1) {
        file = "/index.html";
        file_len = strlen(file);
    }

    strncpy(path, root, root_len);
    strncpy(path + root_len, file, file_len);

    if ((fd = open(path, O_RDONLY)) == -1) {
        perror("Error opening the file on server");
        sprintf(buffer, "%s %s\n", http_text(request->http_version), response_text(HTTP_404_NOT_FOUND));
        write(client, buffer, strlen(buffer));

        return;
    }

    /* The first time search if it raises an error */
    is_partial_file = 0;
    while ((n = read(fd, buffer, sizeof(buffer))) != 0) {
        if (n == -1) {
            is_partial_file = 1;
            break;
        }
    }

    /* The second time send to client the file read */
    lseek(fd, SEEK_SET, 0);

    /* First line of response */
    response = (is_partial_file) ? HTTP_206_PARTIAL_CONTENT : HTTP_200_OK;
    sprintf(buffer, "%s %s\n", http_text(request->http_version), response_text(response));
    write(client, buffer, strlen(buffer));

    if (fstat(fd, &sb) != -1) {
        /* Thx to [1]
         * [1] https://www.tutorialspoint.com/c_standard_library/c_function_ctime.htm
         */
        time(&now);
        sprintf(buffer, "Date: %s", ctime(&now));
        write(client, buffer, strlen(buffer));

        sprintf(buffer, "Content-Type: text/txt; charset=UTF-8\n");
        write(client, buffer, strlen(buffer));

        sprintf(buffer, "Content-Length: %ld\n", sb.st_size);
        write(client, buffer, strlen(buffer));

        sprintf(buffer, "Last-Modified: %s", ctime(&sb.st_mtime));
        write(client, buffer, strlen(buffer));

        sprintf(buffer, "Connection: close\n\n");
        write(client, buffer, strlen(buffer));
    }

    while ((n = read(fd, buffer, sizeof(buffer))) != 0) {
        if (n == -1) {
            break;
        }
        buffer[n] = '\0';
        write(client, buffer, strlen(buffer) + 1);
    }

    close(fd);
}

int
main(int argc, char* argv[])
{
    char* www_path;
    char** headers;
    int headers_num;
    unsigned i;
    int sockfd, clientfd;
    struct sockaddr_in address;
    char client_ip[20];
    socklen_t address_len;
    char buffer[1024];
    request_t request;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <port> [root_path]", argv[0]);
        exit(1);
    }

    www_path = (argc >= 3) ? argv[2] : DEFAULT_WWW;

    /* Max 24 headers for now in memory */
    headers = malloc(sizeof(char*) * 24);

    if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        perror("Error creating a new socket");
        exit(1);
    }

    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(atoi(argv[1]));
    address.sin_family = AF_INET;

    address_len = sizeof(address);

    if (bind(sockfd, (struct sockaddr*)&address, address_len) == -1) {
        perror("Error binding the socket");
        exit(1);
    }

    if (listen(sockfd, 1) == -1) {
        perror("Unable to listen");
        exit(1);
    }

    while (1) {
        if ((clientfd = accept(sockfd, (struct sockaddr*)&address, &address_len)) == -1) {
            perror("Error with client connection, maybe try again later");
            continue;
        }

        get_client_ip(clientfd, client_ip);
        printf("Connection from '%s':\n", client_ip);

        read_headers(&clientfd, headers, &headers_num);

        if (headers_num == 0) {
            sprintf(buffer, "HTTP/1.1 %s\n", response_text(HTTP_400_BAD_REQUEST));
            write(clientfd, buffer, strlen(buffer));
        } else {
            if (parse_first_line(&request, headers[0], strlen(headers[0])) > -1) {
                if (request.method == GET) {
                    read_file(www_path, &request, clientfd);
                } else {
                    /* TODO: allow methods */
                    sprintf(buffer, "%s %s\n", http_text(request.http_version), response_text(HTTP_405_METHOD_NOT_ALLOWED));
                    write(clientfd, buffer, strlen(buffer));
                }
            } else {
                sprintf(buffer, "HTTP/1.1 %s\n", response_text(HTTP_400_BAD_REQUEST));
                write(clientfd, buffer, strlen(buffer));
            }
        }

        for (i = 0; i < headers_num; ++i) {
            free(headers[i]);
        }
        printf("[Connection closed]\n\n");
        close(clientfd);
    }

    close(sockfd);
    return 0;
}