-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutility.c
118 lines (107 loc) · 3.26 KB
/
utility.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
int is_ip(char * IP) {
char localhost[] = "localhost";
char ip_local[] = "127.0.0.1";
if (!strcmp(IP, localhost)) {
IP = ip_local;
}
char * endptr;
long int a;
if ((a = strtol(IP, &endptr, 10))) {
if (a >= 0 && a <= 255) {
int i;
for (i = 0 ; i < 3; i++) {
++endptr;
char * tmp = endptr;
if (*(endptr) == 48 && (*(endptr+1) == 46 || *(endptr+1) == 0) && strtol(endptr, &endptr, 10) == 0) continue;
endptr = tmp;
if (!(a = strtol(endptr, &endptr, 10)) || !(a >= 0 && a <= 255)) {
return 0;
}
}
return 1;
} else {
return 0;
}
} else {
return 0;
}
return 1;
}
void gettime() {
time_t now;
time(&now);
char buff[256];
strcpy(buff, ctime(&now));
buff[strlen(buff)-1]='\0';
printf("%s ", buff);
}
char * parse_request(char *buffer) {
char *end = strstr(buffer, "HTTP/1.1");
int bytes = end - (buffer + 4);
char *clean_str = (char *)malloc(bytes);
memmove(clean_str, buffer + 4, bytes);
*(clean_str + bytes - 1) = '\0';
return clean_str;
}
void write_header(int client_socket, int status, long int file_size) {
char headers[2048];
if (status == 200) {
sprintf(headers,"HTTP/1.1 200 OK\r\n"
"Server: CustomCGI\r\n"
"Content-Type: text/html\r\n"
"Content-Length: %ld\r\n"
"\r\n",
file_size);
} else {
sprintf(headers,"HTTP/1.1 404 NOT FOUND\r\n"
"Server: CustomCGI\r\n"
"Content-Type: text/html\r\n"
"Content-Length: %ld\r\n"
"\r\n",
file_size);
}
write(client_socket, headers, strlen(headers));
}
void GET(int client_socket, char *url, char *htdocs) {
char file_name[2048];
strcpy(file_name, htdocs);
if (0 == strcmp("/", url) || 0 == strlen(url) || 0 == strcmp("/favicon.ico", url)) {
strcat(file_name, "/index.html");
} else {
strcat(file_name, url);
}
//printf("%s\n", file_name);
int file_id = open(file_name, O_RDONLY);
struct stat st;
char page[8192];
int ret_in;
if (-1 == file_id) {
char error_page[2048];
strcpy(error_page, htdocs);
strcat(error_page, "/404page.html");
file_id = open(error_page, O_RDONLY);
fstat(file_id, &st);
write_header(client_socket, 404, st.st_size);
ret_in = read(file_id, page, 8192);
write(client_socket, page, ret_in);
close(file_id);
} else {
fstat(file_id, &st);
//printf("%ld\n", st.st_size);
write_header(client_socket, 200, st.st_size);
while ((ret_in = read(file_id, page, 8192)) > 0) {
int ret_out = 0;
while (ret_out != ret_in) {
ret_out += write(client_socket, page + ret_out, ret_in - ret_out);
}
}
close(file_id);
}
}