-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebserver.c
More file actions
111 lines (94 loc) · 2.76 KB
/
Copy pathwebserver.c
File metadata and controls
111 lines (94 loc) · 2.76 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
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
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#define PORT 8080
#define BUFFER_SIZE 4096
int authorizeConnection(char *buffer){
char *apikey = NULL;
char *start = strstr(buffer, "api_key=");
if (start) {
start += strlen("apikey:");
printf("%s\n", start);
char *end = strchr(start, '&');
if (end){
*end = '\0';
}
apikey = strdup(start);
}
printf("%s\n", apikey);
int comp = strcmp(apikey, "correct_api_key_");
return comp;
}
int readstaticfiles(char *resp, size_t resp_size){
FILE *file;
char filename[] = "./data.json";
size_t bytes_read;
file = fopen(filename, "r");
if (file==NULL){
perror("error opening file;");
return 1;
}
bytes_read = fread(resp, sizeof(char), resp_size-1, file);
if(bytes_read==0 && ferror(file)){
perror("Error reading file");
fclose(file);
return 1;
}
resp[bytes_read] = '\0';
fclose(file);
return 0;
}
int main(){
char buffer[BUFFER_SIZE];
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1){
perror("webserver (socket)");
return 1;
}
printf("socket created succesfully\n");
struct sockaddr_in host_addr;
int host_addrlen = sizeof(host_addr);
host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(PORT);
host_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd, (struct sockaddr *)&host_addr, host_addrlen)!=0){
perror("webserver (bind)");
return 1;
}
printf("socket succesfully bound to address\n");
if(listen(sockfd, SOMAXCONN)!=0){
perror("webserver (listen)");
return 1;
}
printf("socket succesfully listening on address: http://localhost:%d\n", PORT);
for(;;){
int newsockfd = accept(sockfd, (struct sockaddr*)&host_addr, (socklen_t *)&host_addrlen);
if(newsockfd<0){
perror("webserver (accept)");
continue;
}
printf("connection accepted\n");
int valread = read(newsockfd, buffer, BUFFER_SIZE);
if(valread<0){
perror("webserver (read)");
continue;
}
char resp[BUFFER_SIZE];
readstaticfiles(resp, BUFFER_SIZE);
char header[BUFFER_SIZE];
snprintf(header, BUFFER_SIZE,
"HTTP/1.1 200 OK\r\n"
"Content-Length: %zu\r\n"
"Content-Type: text/json\r\n"
"\r\n",
strlen(resp));
if(authorizeConnection(buffer)==0){
write(newsockfd, header, strlen(header));
write(newsockfd, resp, strlen(resp));
close(newsockfd);
}
}
return 0;
}