-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.c
97 lines (81 loc) · 2.41 KB
/
response.c
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
#include "response.h"
#include "server_defines.h"
#include <stdio.h>
#include <time.h>
#include "base.h"
#include "log.h"
char* shock_date_now() {
char *buf = malloc(128);
time_t now = time(0);
struct tm tm = *gmtime(&now);
strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm);
return buf;
}
void shock_response_send_header(SOCKET sock, char* header, char* value)
{
char buf[1024];
sprintf(buf, "%s: %s\r\n", header, value);
send(sock, buf, strlen(buf), 0);
}
void shock_serve_file(SOCKET sock, char* filename)
{
long fsize;
FILE *fp = fopen(filename, "rb");
if (!fp){
shock_error_notfound(sock, "Requested file cannot be found.");
return;
}
shock_send_responseline(sock, 200, "OK", 1);
shock_default_headers(sock);
char* etag = shock_cache_get(filename);
shock_response_send_header(sock, "Etag", etag);
shock_response_end_headers(sock);
long buflen;
char buf[2048];
while (1) {
buflen = fread(buf, 1, sizeof(buf), fp);
if (buflen < 1) {
if (!feof(fp)) {
shock_log(SHOCK_ERROR, "Failed to read %s file", filename);
printf("Internal Server Error: An error occured while reading file: %s \n", filename);
shock_error_internal(sock, "Failed to read data from requested file!");
break;
}
break;
}
send(sock, buf, buflen, 0);
}
fclose(fp);
free(etag);
}
void shock_response_end_headers(SOCKET sock)
{
char buf[16];
sprintf(buf, "\r\n"); // DO NOT DELETE! This seperates the body and headers so!
send(sock, buf, strlen(buf), 0);
}
void shock_default_headers(SOCKET sock)
{
char* date= shock_date_now();
shock_response_send_header(sock, "Date", date);
shock_response_send_header(sock, "Server", SERVER_STRING);
free(date);
}
void shock_send_responseline(SOCKET sock, int status, char* statusMsg, int httpVer)
{
char buf[1024];
sprintf(buf, "HTTP/1.%d %d %s\r\n", httpVer, status, statusMsg);
send(sock, buf, strlen(buf), 0);
}
void shock_response_send_header_i(SOCKET sock, char* header, int value)
{
char buf[1024];
sprintf(buf, "%s: %d\r\n", header, value);
send(sock, buf, strlen(buf), 0);
}
void shock_response_notmodified(SOCKET sock)
{
shock_send_responseline(sock, 304, "Not Modified", 1);
shock_default_headers(sock);
shock_response_end_headers(sock);
}