forked from JeffreytheCoder/Simple-HTTP-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.c
More file actions
71 lines (63 loc) · 2.1 KB
/
http.c
File metadata and controls
71 lines (63 loc) · 2.1 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "http.h"
#include <sys/fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
const int BUFFER_SIZE = 104857600;
const char *get_mime_type(const char *file_ext) {
if (strcasecmp(file_ext, "html") == 0 || strcasecmp(file_ext, "htm") == 0) {
return "text/html";
} else if (strcasecmp(file_ext, "txt") == 0) {
return "text/plain";
} else if (strcasecmp(file_ext, "jpg") == 0 || strcasecmp(file_ext, "jpeg") == 0) {
return "image/jpeg";
} else if (strcasecmp(file_ext, "png") == 0) {
return "image/png";
} else {
return "application/octet-stream";
}
}
void build_http_response(const char *file_name,
const char *file_ext,
char *response,
size_t *response_len) {
// build HTTP header
const char *mime_type = get_mime_type(file_ext);
char *header = (char *)malloc(BUFFER_SIZE * sizeof(char));
snprintf(header, BUFFER_SIZE,
"HTTP/1.1 200 OK\r\n"
"Content-Type: %s\r\n"
"\r\n",
mime_type);
// if file not exist, response is 404 Not Found
int file_fd = open(file_name, O_RDONLY);
if (file_fd == -1) {
snprintf(response, BUFFER_SIZE,
"HTTP/1.1 404 Not Found\r\n"
"Content-Type: text/plain\r\n"
"\r\n"
"404 Not Found");
*response_len = strlen(response);
return;
}
// get file size for Content-Length
struct stat file_stat;
fstat(file_fd, &file_stat);
off_t file_size = file_stat.st_size;
// copy header to response buffer
*response_len = 0;
memcpy(response, header, strlen(header));
*response_len += strlen(header);
// copy file to response buffer
ssize_t bytes_read;
while ((bytes_read = read(file_fd,
response + *response_len,
BUFFER_SIZE - *response_len)) > 0) {
*response_len += bytes_read;
}
free(header);
close(file_fd);
}