-
Notifications
You must be signed in to change notification settings - Fork 2
/
httplib.h
1290 lines (1070 loc) · 34.7 KB
/
httplib.h
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// httplib.h
//
// Copyright (c) 2017 Yuji Hirose. All rights reserved.
// The Boost Software License 1.0
//
#ifndef _CPPHTTPLIB_HTTPLIB_H_
#define _CPPHTTPLIB_HTTPLIB_H_
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_DEPRECATE
#ifndef SO_SYNCHRONOUS_NONALERT
#define SO_SYNCHRONOUS_NONALERT 0x20
#endif
#ifndef SO_OPENTYPE
#define SO_OPENTYPE 0x7008
#endif
#if (_MSC_VER < 1900)
#define snprintf _snprintf_s
#endif
#define S_ISREG(m) (((m)&S_IFREG)==S_IFREG)
#define S_ISDIR(m) (((m)&S_IFDIR)==S_IFDIR)
#include <fcntl.h>
#include <io.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#undef min
#undef max
typedef SOCKET socket_t;
#else
#include <pthread.h>
#include <unistd.h>
#include <netdb.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
typedef int socket_t;
#endif
#include <fstream>
#include <functional>
#include <map>
#include <memory>
//#include <regex>
#include <boost/regex.hpp>
#include <string>
#include <sys/stat.h>
#include <assert.h>
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
#include <openssl/ssl.h>
#endif
namespace httplib
{
typedef std::map<std::string, std::string> Map;
typedef std::multimap<std::string, std::string> MultiMap;
typedef boost::smatch Match;
struct Request {
std::string method;
std::string path;
MultiMap headers;
std::string body;
Map params;
Match matches;
bool has_header(const char* key) const;
std::string get_header_value(const char* key) const;
void set_header(const char* key, const char* val);
bool has_param(const char* key) const;
};
struct Response {
int status;
MultiMap headers;
std::string body;
bool has_header(const char* key) const;
std::string get_header_value(const char* key) const;
void set_header(const char* key, const char* val);
void set_redirect(const char* url);
void set_content(const char* s, size_t n, const char* content_type);
void set_content(const std::string& s, const char* content_type);
Response() : status(-1) {}
};
class Stream {
public:
virtual ~Stream() {}
virtual int read(char* ptr, size_t size) = 0;
virtual int write(const char* ptr, size_t size1) = 0;
virtual int write(const char* ptr) = 0;
};
class SocketStream : public Stream {
public:
SocketStream(socket_t sock);
virtual ~SocketStream();
virtual int read(char* ptr, size_t size);
virtual int write(const char* ptr, size_t size);
virtual int write(const char* ptr);
private:
socket_t sock_;
};
class Server {
public:
typedef std::function<void (const Request&, Response&)> Handler;
typedef std::function<void (const Request&, const Response&)> Logger;
Server();
virtual ~Server();
void get(const char* pattern, Handler handler);
void post(const char* pattern, Handler handler);
bool set_base_dir(const char* path);
void set_error_handler(Handler handler);
void set_logger(Logger logger);
bool listen(const char* host, int port);
void stop();
protected:
void process_request(Stream& strm);
private:
typedef std::vector<std::pair<boost::regex, Handler>> Handlers;
bool routing(Request& req, Response& res);
bool handle_file_request(Request& req, Response& res);
bool dispatch_request(Request& req, Response& res, Handlers& handlers);
bool read_request_line(Stream& strm, Request& req);
virtual bool read_and_close_socket(socket_t sock);
socket_t svr_sock_;
std::string base_dir_;
Handlers get_handlers_;
Handlers post_handlers_;
Handler error_handler_;
Logger logger_;
};
class Client {
public:
Client(const char* host, int port);
virtual ~Client();
std::shared_ptr<Response> get(const char* path);
std::shared_ptr<Response> head(const char* path);
std::shared_ptr<Response> post(const char* path, const std::string& body, const char* content_type);
std::shared_ptr<Response> post(const char* path, const Map& params);
bool send(const Request& req, Response& res);
protected:
bool process_request(Stream& strm, const Request& req, Response& res);
private:
bool read_response_line(Stream& strm, Response& res);
void add_default_headers(Request& req);
virtual bool read_and_close_socket(socket_t sock, const Request& req, Response& res);
const std::string host_;
const int port_;
};
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
class SSLSocketStream : public Stream {
public:
SSLSocketStream(SSL* ssl);
virtual ~SSLSocketStream();
virtual int read(char* ptr, size_t size);
virtual int write(const char* ptr, size_t size);
virtual int write(const char* ptr);
private:
SSL* ssl_;
};
class SSLServer : public Server {
public:
SSLServer(const char* cert_path, const char* private_key_path);
virtual ~SSLServer();
private:
virtual bool read_and_close_socket(socket_t sock);
SSL_CTX* ctx_;
};
class SSLClient : public Client {
public:
SSLClient(const char* host, int port);
virtual ~SSLClient();
private:
virtual bool read_and_close_socket(socket_t sock, const Request& req, Response& res);
SSL_CTX* ctx_;
};
#endif
/*
* Implementation
*/
namespace detail {
template <class Fn>
void split(const char* b, const char* e, char d, Fn fn)
{
int i = 0;
int beg = 0;
while (e ? (b + i != e) : (b[i] != '\0')) {
if (b[i] == d) {
fn(&b[beg], &b[i]);
beg = i + 1;
}
i++;
}
if (i) {
fn(&b[beg], &b[i]);
}
}
inline bool socket_gets(Stream& strm, char* buf, int bufsiz)
{
// TODO: buffering for better performance
size_t i = 0;
for (;;) {
char byte;
auto n = strm.read(&byte, 1);
if (n < 1) {
if (i == 0) {
return false;
} else {
break;
}
}
buf[i++] = byte;
if (byte == '\n') {
break;
}
}
buf[i] = '\0';
return true;
}
template <typename ...Args>
inline void socket_printf(Stream& strm, const char* fmt, const Args& ...args)
{
char buf[BUFSIZ];
auto n = snprintf(buf, BUFSIZ, fmt, args...);
if (n > 0) {
if (n >= BUFSIZ) {
// TODO: buffer size is not large enough...
} else {
strm.write(buf, n);
}
}
}
inline int close_socket(socket_t sock)
{
#ifdef _MSC_VER
return closesocket(sock);
#else
return close(sock);
#endif
}
template <typename T>
inline bool read_and_close_socket(socket_t sock, T callback)
{
SocketStream strm(sock);
auto ret = callback(strm);
close_socket(sock);
return ret;
}
inline int shutdown_socket(socket_t sock)
{
#ifdef _MSC_VER
return shutdown(sock, SD_BOTH);
#else
return shutdown(sock, SHUT_RDWR);
#endif
}
template <typename Fn>
socket_t create_socket(const char* host, int port, Fn fn)
{
#ifdef _MSC_VER
int opt = SO_SYNCHRONOUS_NONALERT;
setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
#endif
// Get address info
struct addrinfo hints;
struct addrinfo *result;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
auto service = std::to_string(port);
if (getaddrinfo(host, service.c_str(), &hints, &result)) {
return -1;
}
for (auto rp = result; rp; rp = rp->ai_next) {
// Create a socket
auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == -1) {
continue;
}
// Make 'reuse address' option available
int yes = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
// bind or connect
if (fn(sock, *rp)) {
freeaddrinfo(result);
return sock;
}
close_socket(sock);
}
freeaddrinfo(result);
return -1;
}
inline socket_t create_server_socket(const char* host, int port)
{
return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
return false;
}
if (listen(sock, 5)) { // Listen through 5 channels
return false;
}
return true;
});
}
inline socket_t create_client_socket(const char* host, int port)
{
return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
if (connect(sock, ai.ai_addr, ai.ai_addrlen)) {
return false;
}
return true;
});
}
inline bool is_file(const std::string& s)
{
struct stat st;
return stat(s.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
}
inline bool is_dir(const std::string& s)
{
struct stat st;
return stat(s.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
}
inline void read_file(const std::string& path, std::string& out)
{
std::ifstream fs(path, std::ios_base::binary);
fs.seekg(0, std::ios_base::end);
auto size = fs.tellg();
fs.seekg(0);
out.resize(static_cast<size_t>(size));
fs.read(&out[0], size);
}
inline std::string file_extension(const std::string& path)
{
//std::cout<<"FILE EXTENSION"<<std::endl;
boost::smatch m;
auto pat = boost::regex("\\.([a-zA-Z0-9]+)$");
if (boost::regex_search(path, m, pat)) {
return m[1].str();
}
return std::string();
}
inline const char* content_type(const std::string& path)
{
auto ext = detail::file_extension(path);
if (ext == "txt") {
return "text/plain";
} else if (ext == "html") {
return "text/html";
} else if (ext == "js") {
return "text/javascript";
} else if (ext == "css") {
return "text/css";
} else if (ext == "xml") {
return "text/xml";
} else if (ext == "jpeg" || ext == "jpg") {
return "image/jpg";
} else if (ext == "png") {
return "image/png";
} else if (ext == "gif") {
return "image/gif";
} else if (ext == "svg") {
return "image/svg+xml";
} else if (ext == "ico") {
return "image/x-icon";
} else if (ext == "json") {
return "application/json";
} else if (ext == "pdf") {
return "application/pdf";
} else if (ext == "xhtml") {
return "application/xhtml+xml";
}
return nullptr;
}
inline const char* status_message(int status)
{
switch (status) {
case 200: return "OK";
case 400: return "Bad Request";
case 404: return "Not Found";
default:
case 500: return "Internal Server Error";
}
}
inline const char* get_header_value(const MultiMap& map, const char* key, const char* def)
{
auto it = map.find(key);
if (it != map.end()) {
return it->second.c_str();
}
return def;
}
inline int get_header_value_int(const MultiMap& map, const char* key, int def)
{
auto it = map.find(key);
if (it != map.end()) {
return std::stoi(it->second);
}
return def;
}
inline bool read_headers(Stream& strm, MultiMap& headers)
{
//std::cout<<"READ HEADERS"<<std::endl;
static boost::regex re("(.+?): (.+?)\r\n");
const auto BUFSIZ_HEADER = 2048;
char buf[BUFSIZ_HEADER];
for (;;) {
if (!socket_gets(strm, buf, BUFSIZ_HEADER)) {
return false;
}
if (!strcmp(buf, "\r\n")) {
break;
}
boost::cmatch m;
if (boost::regex_match(buf, m, re)) {
auto key = std::string(m[1]);
auto val = std::string(m[2]);
headers.insert(std::make_pair(key, val));
}
}
return true;
}
template <typename T>
bool read_content(Stream& strm, T& x)
{
auto len = get_header_value_int(x.headers, "Content-Length", 0);
if (len) {
x.body.assign(len, 0);
auto r = 0;
while (r < len){
auto r_incr = strm.read(&x.body[r], len - r);
if (r_incr <= 0) {
return false;
}
r += r_incr;
}
}
return true;
}
template <typename T>
inline void write_headers(Stream& strm, const T& res)
{
strm.write("Connection: close\r\n");
for (const auto& x: res.headers) {
if (x.first != "Content-Type" && x.first != "Content-Length") {
socket_printf(strm, "%s: %s\r\n", x.first.c_str(), x.second.c_str());
}
}
auto t = get_header_value(res.headers, "Content-Type", "text/plain");
socket_printf(strm, "Content-Type: %s\r\n", t);
socket_printf(strm, "Content-Length: %ld\r\n", res.body.size());
strm.write("\r\n");
}
inline void write_response(Stream& strm, const Request& req, const Response& res)
{
socket_printf(strm, "HTTP/1.0 %d %s\r\n", res.status, status_message(res.status));
write_headers(strm, res);
if (!res.body.empty() && req.method != "HEAD") {
strm.write(res.body.c_str(), res.body.size());
}
}
inline std::string encode_url(const std::string& s)
{
std::string result;
for (auto i = 0; s[i]; i++) {
switch (s[i]) {
case ' ': result += "+"; break;
case '\'': result += "%27"; break;
case ',': result += "%2C"; break;
case ':': result += "%3A"; break;
case ';': result += "%3B"; break;
default:
if (s[i] < 0) {
result += '%';
char hex[4];
size_t len = snprintf(hex, sizeof(hex), "%02X", (unsigned char)s[i]);
assert(len == 2);
result.append(hex, len);
} else {
result += s[i];
}
break;
}
}
return result;
}
inline bool is_hex(char c, int& v)
{
if (0x20 <= c && isdigit(c)) {
v = c - '0';
return true;
} else if ('A' <= c && c <= 'F') {
v = c - 'A' + 10;
return true;
} else if ('a' <= c && c <= 'f') {
v = c - 'a' + 10;
return true;
}
return false;
}
inline int from_hex_to_i(const std::string& s, int i, int cnt, int& val)
{
val = 0;
for (; s[i] && cnt; i++, cnt--) {
int v = 0;
if (is_hex(s[i], v)) {
val = val * 16 + v;
} else {
break;
}
}
return --i;
}
inline size_t to_utf8(int code, char* buff)
{
if (code < 0x0080) {
buff[0] = (code & 0x7F);
return 1;
} else if (code < 0x0800) {
buff[0] = (0xC0 | ((code >> 6) & 0x1F));
buff[1] = (0x80 | (code & 0x3F));
return 2;
} else if (code < 0xD800) {
buff[0] = (0xE0 | ((code >> 12) & 0xF));
buff[1] = (0x80 | ((code >> 6) & 0x3F));
buff[2] = (0x80 | (code & 0x3F));
return 3;
} else if (code < 0xE000) { // D800 - DFFF is invalid...
return 0;
} else if (code < 0x10000) {
buff[0] = (0xE0 | ((code >> 12) & 0xF));
buff[1] = (0x80 | ((code >> 6) & 0x3F));
buff[2] = (0x80 | (code & 0x3F));
return 3;
} else if (code < 0x110000) {
buff[0] = (0xF0 | ((code >> 18) & 0x7));
buff[1] = (0x80 | ((code >> 12) & 0x3F));
buff[2] = (0x80 | ((code >> 6) & 0x3F));
buff[3] = (0x80 | (code & 0x3F));
return 4;
}
// NOTREACHED
return 0;
}
inline std::string decode_url(const std::string& s)
{
std::string result;
for (int i = 0; s[i]; i++) {
if (s[i] == '%') {
i++;
assert(s[i]);
if (s[i] == '%') {
result += s[i];
} else if (s[i] == 'u') {
// Unicode
i++;
assert(s[i]);
int val = 0;
i = from_hex_to_i(s, i, 4, val);
char buff[4];
size_t len = to_utf8(val, buff);
if (len > 0) {
result.append(buff, len);
}
} else {
// HEX
int val = 0;
i = from_hex_to_i(s, i, 2, val);
result += val;
}
} else if (s[i] == '+') {
result += ' ';
} else {
result += s[i];
}
}
return result;
}
inline void write_request(Stream& strm, const Request& req)
{
auto path = encode_url(req.path);
socket_printf(strm, "%s %s HTTP/1.0\r\n", req.method.c_str(), path.c_str());
write_headers(strm, req);
if (!req.body.empty()) {
if (req.has_header("application/x-www-form-urlencoded")) {
auto str = encode_url(req.body);
strm.write(str.c_str(), str.size());
} else {
strm.write(req.body.c_str(), req.body.size());
}
}
}
inline void parse_query_text(const std::string& s, Map& params)
{
split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
std::string key;
std::string val;
split(b, e, '=', [&](const char* b, const char* e) {
if (key.empty()) {
key.assign(b, e);
} else {
val.assign(b, e);
}
});
params[key] = detail::decode_url(val);
});
}
#ifdef _MSC_VER
class WSInit {
public:
WSInit() {
WSADATA wsaData;
WSAStartup(0x0002, &wsaData);
}
~WSInit() {
WSACleanup();
}
};
static WSInit wsinit_;
#endif
} // namespace detail
// Request implementation
inline bool Request::has_header(const char* key) const
{
return headers.find(key) != headers.end();
}
inline std::string Request::get_header_value(const char* key) const
{
return detail::get_header_value(headers, key, "");
}
inline void Request::set_header(const char* key, const char* val)
{
headers.insert(std::make_pair(key, val));
}
inline bool Request::has_param(const char* key) const
{
return params.find(key) != params.end();
}
// Response implementation
inline bool Response::has_header(const char* key) const
{
return headers.find(key) != headers.end();
}
inline std::string Response::get_header_value(const char* key) const
{
return detail::get_header_value(headers, key, "");
}
inline void Response::set_header(const char* key, const char* val)
{
headers.insert(std::make_pair(key, val));
}
inline void Response::set_redirect(const char* url)
{
set_header("Location", url);
status = 302;
}
inline void Response::set_content(const char* s, size_t n, const char* content_type)
{
body.assign(s, n);
set_header("Content-Type", content_type);
}
inline void Response::set_content(const std::string& s, const char* content_type)
{
body = s;
set_header("Content-Type", content_type);
}
// Socket stream implementation
inline SocketStream::SocketStream(socket_t sock): sock_(sock)
{
}
inline SocketStream::~SocketStream()
{
}
inline int SocketStream::read(char* ptr, size_t size)
{
return recv(sock_, ptr, size, 0);
}
inline int SocketStream::write(const char* ptr, size_t size)
{
return send(sock_, ptr, size, 0);
}
inline int SocketStream::write(const char* ptr)
{
return write(ptr, strlen(ptr));
}
// HTTP server implementation
inline Server::Server()
: svr_sock_(-1)
{
}
inline Server::~Server()
{
}
inline void Server::get(const char* pattern, Handler handler)
{
//std::cout<<"GET"<<std::endl;
get_handlers_.push_back(std::make_pair(boost::regex(pattern), handler));
}
inline void Server::post(const char* pattern, Handler handler)
{
//std::cout<<"POST"<<std::endl;
post_handlers_.push_back(std::make_pair(boost::regex(pattern), handler));
}
inline bool Server::set_base_dir(const char* path)
{
if (detail::is_dir(path)) {
base_dir_ = path;
return true;
}
return false;
}
inline void Server::set_error_handler(Handler handler)
{
error_handler_ = handler;
}
inline void Server::set_logger(Logger logger)
{
logger_ = logger;
}
inline bool Server::listen(const char* host, int port)
{
svr_sock_ = detail::create_server_socket(host, port);
if (svr_sock_ == -1) {
return false;
}
auto ret = true;
for (;;) {
socket_t sock = accept(svr_sock_, NULL, NULL);
if (sock == -1) {
if (svr_sock_ != -1) {
detail::close_socket(svr_sock_);
ret = false;
} else {
; // The server socket was closed by user.
}
break;
}
// TODO: should be async
read_and_close_socket(sock);
}
return ret;
}
inline void Server::stop()
{
detail::shutdown_socket(svr_sock_);
detail::close_socket(svr_sock_);
svr_sock_ = -1;
}
inline bool Server::read_request_line(Stream& strm, Request& req)
{
//std::cout<<"READ REQUEST LINE"<<std::endl;
const auto BUFSIZ_REQUESTLINE = 2048;
char buf[BUFSIZ_REQUESTLINE];
if (!detail::socket_gets(strm, buf, BUFSIZ_REQUESTLINE)) {
return false;
}
//std::cout<<"GET HEAD POST REGEX"<<std::endl;
// std::cout<<buf<<std::endl;
// if(std::string(buf)=="GET /event.html HTTP/1.1")
if(std::strcmp(buf,"GET /event.html HTTP/1.1")==0)
{
std::cout<<"YEP"<<std::endl;
req.method="GET";
req.path=detail::decode_url("/event.html");
return true;
}
static boost::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
//std::cout<<"OKAY REGEX EXISTS"<<std::endl;
boost::cmatch m;
//std::cout<<"MATCHING NOW"<<std::endl;
if (boost::regex_match(buf, m, re)) {
req.method = std::string(m[1]);
req.path = detail::decode_url(m[2]);
// Parse query text
auto len = std::distance(m[3].first, m[3].second);
if (len > 0) {
detail::parse_query_text(m[3], req.params);
}
return true;
}
return false;
}
inline bool Server::handle_file_request(Request& req, Response& res)
{
if (!base_dir_.empty()) {
std::string path = base_dir_ + req.path;
if (!path.empty() && path.back() == '/') {
path += "index.html";
}
if (detail::is_file(path)) {
detail::read_file(path, res.body);
auto type = detail::content_type(path);
if (type) {
res.set_header("Content-Type", type);
}
res.status = 200;
return true;
}
}
return false;
}
inline bool Server::routing(Request& req, Response& res)
{
if (req.method == "GET" && handle_file_request(req, res)) {
return true;
}
if (req.method == "GET" || req.method == "HEAD") {
return dispatch_request(req, res, get_handlers_);
} else if (req.method == "POST") {
return dispatch_request(req, res, post_handlers_);
}
return false;
}
inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
{
//std::cout<<"DISPATCH REQUEST"<<std::endl;
for (const auto& x: handlers) {
const auto& pattern = x.first;
const auto& handler = x.second;
if (boost::regex_match(req.path, req.matches, pattern)) {
handler(req, res);
return true;
}
}
return false;
}
inline void Server::process_request(Stream& strm)
{
Request req;
Response res;
if (!read_request_line(strm, req) ||
!detail::read_headers(strm, req.headers)) {
// TODO:
return;
}
if (req.method == "POST") {
if (!detail::read_content(strm, req)) {
// TODO:
return;