-
Notifications
You must be signed in to change notification settings - Fork 1
/
response.c
87 lines (79 loc) · 1.58 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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h>
#include <fcntl.h>
#include "response.h"
// Status Codes
char *text_200 = "HTTP/1.1 200 OK\n";
char *text_404 = "HTTP/1.1 404 Not Found\n";
char *text_405 = "HTTP/1.1 405 Method Not Allowed\n";
void response(int sock_fd, int status_code)
{
if (status_code == OK)
{
write(sock_fd, text_200, strlen(text_200));
write(sock_fd, "\n", 1);
}
else if (status_code == NOT_FOUND)
{
write(sock_fd, text_404, strlen(text_404));
write(sock_fd, "\n", 1);
}
else
{
write(sock_fd, text_405, strlen(text_405));
write(sock_fd, "\n", 1);
}
}
int get_response_code(char *method, char *path)
{
if (!(strcasecmp(method, "GET") == 0 || strcasecmp(method, "HEAD") == 0))
{
return METHOD_NOT_ALLOWED;
}
int fd = open(path, O_RDONLY);
if (fd == -1)
{
return NOT_FOUND;
}
close(fd);
return OK;
}
void response_body(int sock_fd, char *path, int status_code)
{
if (status_code == OK)
{
int fd = open(path, O_RDONLY);
int bytes_read;
if (fd == -1)
{
perror("server: file");
exit(1);
}
char *buffer = malloc(1024);
while ((bytes_read = read(fd, buffer, 1024)) > 0)
{
write(sock_fd, buffer, bytes_read);
}
}
else if (status_code == NOT_FOUND)
{
write(sock_fd, "<h1>404 Not Found!</h1>\n", 25);
}
else
{
write(sock_fd, "<h1>405 Method Not Allowed!</h1>\n", 25);
}
return;
}