Repository navigation
Expand file tree
/
Copy pathsimple_http_serv.hpp
More file actions
656 lines (510 loc) · 16.3 KB
/
Copy pathsimple_http_serv.hpp
File metadata and controls
656 lines (510 loc) · 16.3 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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <vector>
#include <cctype>
#include <thread>
#include <unordered_map>
#include <time.h>
#include <fstream>
#include <sstream>
#include <set>
#define MAX_EVENTS 64
#define buff_size 512
#define timeout 5.0
#define max_clients 10
std::string ipp;
std::string mount_point;
struct resource{
std::string file_path;
std::string content_type;
};
struct http_request{
std::string method;
std::string target;
std::string http_version;
std::unordered_map<std::string, std::string> headers;
std::string buff;
void reset(){
method.clear();
target.clear();
http_version.clear();
headers.clear();
}
};
struct client_rr{
http_request request;
std::string response;
time_t start = time(0);
bool close_after_send = false;
bool send = false;
bool bad_request = false;
bool timed_out = false;
bool unsupported_version = false;
bool no_resource = false;
bool keep_alive = true;
bool unsupported_method = false;
};
bool is_ws(char c){
return c == ' ' || c == '\t';
}
bool is_token(char c){
if(std::isalnum(static_cast<unsigned char>(c)))
return true;
if(c == '!' || c == '#' || c == '$' || c == '%' || c == '&' ||
c == '\'' || c == '*' || c == '+' || c == '-' || c == '.' ||
c == '^' || c == '_' || c == '`' || c == '|' || c == '~')
return true;
return false;
}
bool is_pchar(char c){
if(std::isalnum(static_cast<unsigned char>(c)))
return true;
if(c == '-' || c == '.' || c == '_' || c == '~' || c == '!' || c == '$' ||
c == '&' || c == '\'' || c == '(' || c == ')' || c == '*' || c == '+' ||
c == ',' || c == ';' || c == '=' || c == ':' || c == '@')
return true;
return false;
}
bool is_vchar(char c){
return c >= '!' && c <= '~';
}
bool get_method(std::string& s, const std::string& buff, size_t& index, const size_t end){
if(index >= end || !is_token(buff[index]))
return false;
int start = index;
while(index < end && is_token(buff[index])){
++index;
}
if(index >= end || buff[index] != ' ')
return false;
s.append(buff, start, index - start);
++index;
return true;
}
bool get_target(std::string& s, const std::string& buff, size_t& index, const size_t end){
if(index >= end || buff[index] != '/')
return false;
int start = index;
while(index < end && (is_pchar(buff[index]) || buff[index] == '/' || buff[index] == '%')){
if(buff[index] == '%'){
if(index + 2 >= end)
return false;
if(!std::isxdigit(static_cast<unsigned char>(buff[index + 1])) || !std::isxdigit(static_cast<unsigned char>(buff[index + 2])))
return false;
index += 3;
continue;
}
++index;
}
if(index < end && buff[index] == '?'){
++index;
while(index < end && (is_pchar(buff[index]) || buff[index] == '?' || buff[index] == '/' || buff[index] == '%')){
if(buff[index] == '%'){
if(index + 2 >= end)
return false;
if(!std::isxdigit(static_cast<unsigned char>(buff[index + 1])) || !std::isxdigit(static_cast<unsigned char>(buff[index + 2])))
return false;
index += 3;
continue;
}
++index;
}
}
if(index >= end || buff[index] != ' ')
return false;
s.append(buff, start, index - start);
++index;
return true;
}
bool get_version(std::string& s, const std::string& buff, size_t& index, const size_t end){
int start = index;
while(index < end && buff[index] != '\r')
++index;
if(index + 1 >= end)
return false;
if(buff[index] != '\r' || buff[index + 1] != '\n')
return false;
s.append(buff, start, index - start);
index+=2;
if(s == "HTTP/1.0")
return true;
if(s == "HTTP/1.1")
return true;
return false;
}
bool get_field_name(std::string& s, const std::string& buff, size_t& index, const size_t end){
if(index >= end || !is_token(buff[index]))
return false;
size_t start = index;
while(index < end && is_token(buff[index]))
++index;
if(index >= end || buff[index] != ':')
return false;
s.append(buff, start, index - start);
++index;
return true;
}
bool get_field_value(std::string& s, const std::string& buff, size_t& index, const size_t end){
while(index < end && is_ws(buff[index]))
++index;
if(index >= end)
return false;
size_t start = index;
while(index < end && (is_ws(buff[index]) || is_vchar(buff[index])))
++index;
if(index >= end || buff[index] != '\r')
return false;
if(index + 1 >= end || buff[index + 1] != '\n')
return false;
size_t back = index;
while(back > start && is_ws(buff[back - 1]))
--back;
s.append(buff, start, back - start);
index += 2;
return true;
}
bool get_headers(std::unordered_map<std::string, std::string>& headers, const std::string& buff, size_t& index, const size_t end){
while(index < end){
std::string hf, fv;
if(!get_field_name(hf, buff, index, end))
return false;
if(headers.count(hf) > 0)
return false;
if(!get_field_value(fv, buff, index, end))
return false;
headers[hf] = fv;
}
return true;
}
bool handle_request(http_request& request, const size_t end){
size_t index = 0;
if(!get_method(request.method, request.buff, index, end + 2))
return false;
if(!get_target(request.target, request.buff, index, end + 2))
return false;
if(!get_version(request.http_version, request.buff, index, end + 2))
return false;
if(!get_headers(request.headers, request.buff, index, end + 2))
return false;
return true;
}
std::unordered_map<std::string, resource> resources;
bool check_method(const std::string& method){
return method == "GET" || method == "HEAD";
}
bool check_target(const std::string& target){
return resources.find(target) != resources.end();
}
bool check_version(const std::string& version){
return version == "HTTP/1.0" || version == "HTTP/1.1";
}
bool check_headers(std::unordered_map<std::string, std::string>& headers){
if(headers.find("Host") == headers.end())
return false;
if(headers["Host"] != ipp)
return false;
if(headers.find("Content-Length") != headers.end() && stoi(headers["Content-Length"]) > 0)
return false;
if(headers.find("Transfer-Encoding") != headers.end())
return false;
return true;
}
void interperet_request(client_rr& client){
http_request& request = client.request;
if(!check_method(request.method))
client.unsupported_method = true;
if(!check_target(request.target))
client.no_resource = true;
if(!check_version(request.http_version))
client.unsupported_version = true;
if(!check_headers(request.headers))
client.bad_request = true;
if(request.headers.find("Connection") != request.headers.end()){
const std::string& s = request.headers.at("Connection");
if(s == "close" || s == "Close" || s == "CLOSE")
client.keep_alive = false;
}
}
void gen_response(client_rr& client){
std::string& response = client.response;
http_request& cur_req = client.request;
time_t t = time(nullptr);
tm t_m{};
gmtime_r(&t, &t_m);
char buff[32];
strftime(buff, sizeof(buff), "%a, %d %b %Y %H:%M:%S GMT", &t_m);
std::string date(buff);
client.close_after_send = true;
if(client.bad_request){
response = "HTTP/1.1 400 Bad Request\r\n"
"Date: " + date + "\r\n"
"Connection: close\r\n\r\n";
return;
}
if(client.unsupported_method){
response = "HTTP/1.1 405 Method Not Allowed\r\n"
"Date: " + date + "\r\n"
"Connection: close\r\n\r\n";
return;
}
if(client.timed_out){
response = "HTTP/1.1 408 Request Timeout\r\n"
"Date: " + date + "\r\n"
"Connection: close\r\n\r\n";
return;
}
if(client.no_resource){
response = "HTTP/1.1 404 Not Found\r\n"
"Date: " + date + "\r\n"
"Connection: close\r\n\r\n";
return;
}
if(client.unsupported_version){
response = "HTTP/1.1 505 Version Not Supported\r\n"
"Date: " + date + "\r\n"
"Connection: close\r\n\r\n";
return;
}
std::ifstream file_to_send(resources[cur_req.target].file_path, std::ios::binary);
if(!file_to_send.is_open() ){
file_to_send.close();
response = "HTTP/1.1 500 Internal Server Error\r\n"
"Date: " + date + "\r\n"
"Connection: close\r\n\r\n";
return;
}
std::ostringstream oss;
oss << file_to_send.rdbuf();
std::string body = oss.str();
std::string body_len;
std::string connection;
if(!client.keep_alive)
connection = "Connection: close\r\n";
else{
connection = "Connection: keep-alive\r\n";
client.close_after_send = false;
}
response = "HTTP/1.1 200 OK\r\n"
"Date: " + date + "\r\n"
"Content-Type: " + resources[cur_req.target].content_type + "\r\n" +
connection +
"Content-Length: " + std::to_string(body.size()) + "\r\n\r\n" + body;
}
void set_mount_point(const std::string& mount_p){
mount_point = mount_p;
}
void add_resource(const std::string& abs_path, const std::string& file_path, const std::string& content_type){
resources[abs_path] = resource{mount_point + file_path, content_type};
}
void handle_client(int epollfd){
int nfds, clientfd;
char recv_buff[buff_size];
epoll_event ev, events[MAX_EVENTS];
bool alive;
std::unordered_map<int, client_rr> clients;
struct client_timer{
std::unordered_map<int, client_rr>* clients;
bool operator()(const int a, const int b) const{
if(clients->at(a).start != clients->at(b).start)
return clients->at(a).start < clients->at(b).start;
return a < b;
}
};
client_timer ct{&clients};
std::set<int, client_timer> client_timers(ct);
while(1){
if(nfds == -1){
std::cerr << "epoll wait\n";
std::exit(EXIT_FAILURE);
}
nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
for(int n = 0; n < nfds; ++n){
clientfd = events[n].data.fd;
alive = true;
if(clients.find(clientfd) == clients.end()){
clients.emplace(clientfd, client_rr{});
client_timers.emplace(clientfd);
}
http_request& cur_req = clients.at(clientfd).request;
while(true){
if(!clients.at(clientfd).send){
ssize_t bytes_recv = recv(clientfd, recv_buff, buff_size, 0);
if(bytes_recv == -1){
if(errno == EAGAIN || errno == EWOULDBLOCK){
break;
}
if(errno == EPIPE || errno == ECONNRESET){
alive = false;
client_timers.erase(clientfd);
close(clientfd);
clients.erase(clientfd);
break;
}
std::cerr << "Error receiving on client: " << clientfd << std::endl;
std::exit(EXIT_FAILURE);
}
if(bytes_recv == 0){
alive = false;
client_timers.erase(clientfd);
close(clientfd);
clients.erase(clientfd);
break;
}
cur_req.buff.append(recv_buff, bytes_recv);
size_t position = cur_req.buff.find("\r\n\r\n");
if(position != std::string::npos){
clients.at(clientfd).send = true;
client_timers.erase(clientfd);
clients.at(clientfd).start = time(0);
client_timers.emplace(clientfd);
if(!handle_request(cur_req, position)){
std::cout << "request parsing failed\n";
clients.at(clientfd).close_after_send = true;
clients.at(clientfd).bad_request = true;
break;
}
interperet_request(clients.at(clientfd));
cur_req.buff.erase(0, position + 4);
}
}
else{
gen_response(clients.at(clientfd));
cur_req.reset();
std::string& response = clients.at(clientfd).response;
ssize_t bytes_sent = send(clientfd, response.c_str(), response.size(), MSG_NOSIGNAL);
if(bytes_sent == -1){
if(errno == EAGAIN || errno == EWOULDBLOCK){
break;
}
if(errno == EPIPE || errno == ECONNRESET){
alive = false;
client_timers.erase(clientfd);
close(clientfd);
clients.erase(clientfd);
break;
}
std::cerr << "Error sending on client: " << clientfd << std::endl;
std::exit(EXIT_FAILURE);
}
if(bytes_sent == response.size()){
if(clients.at(clientfd).close_after_send){
alive = false;
client_timers.erase(clientfd);
close(clientfd);
clients.erase(clientfd);
break;
}
clients.at(clientfd).send = false;
client_timers.erase(clientfd);
clients.at(clientfd).start = time(0);
client_timers.emplace(clientfd);
break;
}
response.erase(0, bytes_sent);
}
}
if(!alive)
continue;
if(!clients.at(clientfd).send){
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = clientfd;
if(epoll_ctl(epollfd, EPOLL_CTL_MOD, clientfd, &ev) == -1){
if(errno == ENOENT)
continue;
std::cerr << "epoll_ctl: " << clientfd << std::endl;
std::exit(EXIT_FAILURE);
}
}
else{
ev.events = EPOLLOUT | EPOLLET;
ev.data.fd = clientfd;
if(epoll_ctl(epollfd, EPOLL_CTL_MOD, clientfd, &ev) == -1){
if(errno == ENOENT)
continue;
std::cerr << "epoll_ctl: " << clientfd << std::endl;
std::exit(EXIT_FAILURE);
}
}
}
auto index = client_timers.begin();
while(index != client_timers.end()){
clientfd = *index;
client_rr& cur = clients.at(clientfd);
double time_alive = difftime(time(0), cur.start);
if(time_alive > timeout){
index = client_timers.erase(index);
close(clientfd);
clients.erase(clientfd);
continue;
}
break;
}
}
}
void accept_loop(int servfd, int* epollfds, int thread_count){
int clientfd;
epoll_event ev;
sockaddr_storage cli_addr{};
socklen_t cli_len = sizeof(cli_addr);
int epollfd = 0;
while(1){
clientfd = accept4(servfd, (sockaddr*)&cli_addr, &cli_len, SOCK_NONBLOCK);
epollfd = epollfd % thread_count;
if(clientfd == -1){
std::cerr << "accept\n";
std::exit(EXIT_FAILURE);
}
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = clientfd;
if(epoll_ctl(epollfds[epollfd], EPOLL_CTL_ADD, clientfd, &ev) == -1){
std::cerr << "epoll_ctl: " << clientfd << std::endl;
std::exit(EXIT_FAILURE);
}
++epollfd;
cli_len = sizeof(cli_addr);
}
}
void start_server(std::string ip, std::string port, int thread_count){
int serv_addr, servfd, nfds;
int epollfds[thread_count];
addrinfo hints{};
addrinfo* results, *result_p;
epoll_event ev, events[MAX_EVENTS];
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
hints.ai_family = AF_UNSPEC;
ipp = ip + ":" + port;
serv_addr = getaddrinfo(ip.c_str(), port.c_str(), &hints, &results);
if(serv_addr != 0){
std::cerr << "getaddrinfo: " << gai_strerror(serv_addr) << std::endl;
std::exit(EXIT_FAILURE);
}
for(result_p = results; result_p != nullptr; result_p = result_p->ai_next){
servfd = socket(result_p->ai_family, result_p->ai_socktype, result_p->ai_protocol);
if(servfd == -1)
continue;
if(bind(servfd, result_p->ai_addr, result_p->ai_addrlen) == 0){
break;
}
close(servfd);
}
freeaddrinfo(results);
if(result_p == nullptr){
std::cerr << "Couldn't bind socket\n";
std::exit(EXIT_FAILURE);
}
if(listen(servfd, SOMAXCONN) != 0){
std::cerr << "failed listen\n";
std::exit(EXIT_FAILURE);
}
for(int i = 0; i < thread_count; ++i){
epollfds[i] = epoll_create1(0);
std::thread(handle_client, epollfds[i]).detach();
}
accept_loop(servfd, epollfds, thread_count);
}