-
Notifications
You must be signed in to change notification settings - Fork 0
/
httplib.c
318 lines (269 loc) · 6.44 KB
/
httplib.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*
* MIT License
* Copyright (C) 2020 Arthur Kupriyanov
*
* HTTP Server inspired by :
*
* laobubu, Wuhan, P.R.China
* https://gist.github.com/laobubu/d6d0e9beb934b60b2e552c2d03e1409e
*
* Abhijeet Rastogi, San Francisco Bay Area
* http://blog.abhijeetr.com/2010/04/very-simple-http-server-writen-in-c.html
*
*/
#include "httplib.h"
#include "static.h"
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#define CONNMAX 1000
#define STATIC_MAX 100
static int listenfd, clients[CONNMAX];
static void start_server(const char *);
static void respond(int);
static char *files[STATIC_MAX];
struct http_header
{
char *name, *value;
};
struct serve_thread_args
{
int clientfd;
};
void *serve_pthread(void *args_p)
{
struct serve_thread_args *args = (struct serve_thread_args *)args_p;
respond(args->clientfd);
return NULL;
}
void serve_wrapper(int clientfd)
{
pthread_t thread;
struct serve_thread_args *args = malloc(sizeof(struct serve_thread_args));
args->clientfd = clientfd;
pthread_create(&thread, NULL, serve_pthread, args);
}
/**
* Serves for passed PORT
*
* This function uses clients array if file descriptors,
* but access for this files will be only from on thread
*
* However, request serving will be proceeded on multiple threads
*/
void serve_forever(const char *PORT)
{
struct sockaddr_in clientaddr;
socklen_t addrlen;
int slot = 0;
fprintf(stderr, "Server started %shttp://127.0.0.1:%s%s\n", "\033[92m", PORT, "\033[0m");
int i;
for (i = 0; i < CONNMAX; i++)
clients[i] = -1; // there is no client connected
start_server(PORT);
// Ignore SIGCHLD to avoid zombie threads
signal(SIGCHLD, SIG_IGN);
// ACCEPT connections
while (1)
{
addrlen = sizeof(clientaddr);
clients[slot] = accept(listenfd, (struct sockaddr *)&clientaddr, &addrlen);
if (clients[slot] < 0)
{
perror("trying to accept requests");
}
else
{
serve_wrapper(clients[slot]);
}
while (clients[slot] != -1)
slot = (slot + 1) % CONNMAX; // move client pointer
}
}
// start server
void start_server(const char *port)
{
static_files(files);
struct addrinfo hints, *res, *p;
// getaddrinfo for host
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if (getaddrinfo(NULL, port, &hints, &res) != 0)
{
perror("getaddrinfo() error");
exit(1);
}
// socket and bind
for (p = res; p != NULL; p = p->ai_next)
{
int option = 1;
listenfd = socket(p->ai_family, p->ai_socktype, 0);
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
if (listenfd == -1)
continue;
if (bind(listenfd, p->ai_addr, p->ai_addrlen) == 0)
break;
}
if (p == NULL)
{
perror("socket() or bind()");
exit(1);
}
freeaddrinfo(res);
// listen for incoming connections
if (listen(listenfd, 1000000) != 0)
{
perror("listen() error");
exit(1);
}
}
// get request header
char *request_header(const char *name)
{
struct http_header reqhdr[17] = {{"\0", "\0"}};
struct http_header *h = reqhdr;
while (h->name)
{
if (strcmp(h->name, name) == 0)
return h->value;
h++;
}
return NULL;
}
void respond(int clientfd)
{
int rcvd;
char *buf = malloc(65535);
rcvd = recv(clientfd, buf, 65535, 0);
if (rcvd < 0)
{
// receive error
fprintf(stderr, ("recv() error\n"));
}
else if (rcvd == 0)
{
fprintf(stderr, "Client disconnected upexpectedly.\n");
}
else
{
// message received
buf[rcvd] = '\0';
method = strtok(buf, " \t\r\n");
uri = strtok(NULL, " \t");
prot = strtok(NULL, " \t\r\n");
fprintf(stderr, "\x1b[32m + [%s] %s\x1b[0m\n", method, uri);
if ((qs = strchr(uri, '?')) != NULL)
{
*qs++ = '\0'; // split URI
}
else
{
qs = uri - 1; // use an empty string
}
struct http_header reqhdr[17] = {{"\0", "\0"}};
struct http_header *h = reqhdr;
char *t = (char *)malloc(sizeof(char));
char *t2 = (char *)malloc(sizeof(char));
while (h < reqhdr + 16)
{
char *k, *v, *t;
k = strtok(NULL, "\r\n: \t");
if (!k)
break;
v = strtok(NULL, "\r\n");
while (*v && *v == ' ')
v++;
h->name = k;
h->value = v;
h++;
fprintf(stderr, "[H] %s: %s\n", k, v);
t = v + 1 + strlen(v);
if (t[1] == '\r' && t[2] == '\n')
break;
}
t++; // now the *t shall be the beginning of user payload
t2 = request_header("Content-Length"); // and the related header if there is
payload = t;
payload_size = t2 ? atol(t2) : (rcvd - (t - buf));
// bind clientfd to stdout, making it easier to write
// but not recommended, i think so :)
dup2(clientfd, STDOUT_FILENO);
close(clientfd);
// call router
route();
// tidy up
fflush(stdout);
shutdown(STDOUT_FILENO, SHUT_WR);
close(STDOUT_FILENO);
}
// Closing SOCKET
shutdown(
clientfd,
SHUT_RDWR); // All further send and recieve operations are DISABLED...
close(clientfd);
clientfd = -1;
}
/*
* Write HTTP/1.1 OK (200) status to client socket
* with Content-Type: text/html
*/
void response_ok()
{
printf("HTTP/1.1 200 OK\n");
printf("Content-Type: text/html\r\n\r\n");
}
/*
* Write HTTP/1.1 OK (200) status to client socket
* with Content-Type: text/css
*/
void response_css_media()
{
printf("HTTP/1.1 200 OK\n");
printf("Content-Type: text/css\r\n\r\n");
}
int ends_with(const char *str, const char *suffix)
{
if (!str || !suffix)
return 0;
size_t lenstr = strlen(str);
size_t lensuffix = strlen(suffix);
if (lensuffix > lenstr)
return 0;
return strncmp(str + lenstr - lensuffix, suffix, lensuffix) == 0;
}
int serve_static(char *uri)
{
char web_path[MAX_FILE_NAME_LENGTH];
int index = 0;
char *static_route_path = strcmp("/", uri) == 0 ? "index.html" : ++uri;
sprintf(web_path, "static/%s", static_route_path);
while (files[index] != NULL)
{
if (strcmp(files[index], web_path) == 0)
{
if (ends_with(web_path, ".css"))
{
response_css_media();
}
else
{
response_ok();
}
write_file(files[index]);
return 0;
}
index++;
}
return 1;
}