forked from JeffreytheCoder/Simple-HTTP-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.c
More file actions
53 lines (43 loc) · 1.52 KB
/
server.c
File metadata and controls
53 lines (43 loc) · 1.52 KB
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
#include "server.h"
#include "http.h"
#include "file.h"
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
void *handle_client(void *arg) {
int client_fd = *((int *)arg);
char *buffer = (char *)malloc(BUFFER_SIZE * sizeof(char));
// receive request data from client and store into buffer
ssize_t bytes_received = recv(client_fd, buffer, BUFFER_SIZE, 0);
if (bytes_received > 0) {
// check if request is GET
regex_t regex;
regcomp(®ex, "^GET /([^ ]*) HTTP/1", REG_EXTENDED);
regmatch_t matches[2];
if (regexec(®ex, buffer, 2, matches, 0) == 0) {
// extract filename from request and decode URL
buffer[matches[1].rm_eo] = '\0';
const char *url_encoded_file_name = buffer + matches[1].rm_so;
char *file_name = decode_url(url_encoded_file_name);
// get file extension
char file_ext[32];
strcpy(file_ext, get_file_extension(file_name));
// build HTTP response
char *response = (char *)malloc(BUFFER_SIZE * 2 * sizeof(char));
size_t response_len;
build_http_response(file_name, file_ext, response, &response_len);
// send HTTP response to client
send(client_fd, response, response_len, 0);
free(response);
free(file_name);
}
regfree(®ex);
}
close(client_fd);
free(arg);
free(buffer);
return NULL;
}