-
Notifications
You must be signed in to change notification settings - Fork 20
/
kthttp.h
1392 lines (1378 loc) · 43.3 KB
/
kthttp.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
/*************************************************************************************************
* HTTP utilities
* Copyright (C) 2009-2012 FAL Labs
* This file is part of Kyoto Tycoon.
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version
* 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*************************************************************************************************/
#ifndef _KTHTTP_H // duplication check
#define _KTHTTP_H
#include <ktcommon.h>
#include <ktutil.h>
#include <ktsocket.h>
#include <ktthserv.h>
namespace kyototycoon { // common namespace
/**
* URL accessor.
*/
class URL {
public:
/**
* Default constructor.
*/
explicit URL() :
scheme_(""), host_(""), port_(0), authority_(""),
path_(""), query_(""), fragment_("") {
_assert_(true);
}
/**
* Constructor.
* @param expr the string expression of the URL.
*/
explicit URL(const std::string& expr) :
scheme_(""), host_(""), port_(0), authority_(""),
path_(""), query_(""), fragment_("") {
_assert_(true);
parse_expression(expr);
}
/**
* Copy constructor.
* @param src the source object.
*/
explicit URL(const URL& src) :
scheme_(src.scheme_), host_(src.host_), port_(src.port_), authority_(src.authority_),
path_(src.path_), query_(src.query_), fragment_(src.fragment_) {
_assert_(true);
}
/**
* Destructor
*/
~URL() {
_assert_(true);
}
/**
* Set the string expression of the URL.
*/
void set_expression(const std::string& expr) {
_assert_(true);
parse_expression(expr);
}
/**
* Set the scheme.
*/
void set_scheme(const std::string& scheme) {
_assert_(true);
scheme_ = scheme;
}
/**
* Set the host name.
*/
void set_host(const std::string& host) {
_assert_(true);
host_ = host;
}
/**
* Set the port number.
*/
void set_port(int32_t port) {
_assert_(true);
port_ = port;
}
/**
* Set the authority information.
*/
void set_authority(const std::string& authority) {
_assert_(true);
authority_ = authority;
}
/**
* Set the path.
*/
void set_path(const std::string& path) {
_assert_(true);
path_ = path;
}
/**
* Set the query string.
*/
void set_query(const std::string& query) {
_assert_(true);
query_ = query;
}
/**
* Set the fragment string.
*/
void set_fragment(const std::string& fragment) {
_assert_(true);
fragment_ = fragment;
}
/**
* Get the string expression of the URL.
* @return the string expression of the URL.
*/
std::string expression() {
_assert_(true);
std::string expr;
if (!scheme_.empty()) {
kc::strprintf(&expr, "%s://", scheme_.c_str());
if (!authority_.empty()) kc::strprintf(&expr, "%s@", authority_.c_str());
if (!host_.empty()) {
kc::strprintf(&expr, "%s", host_.c_str());
if (port_ > 0 && port_ != default_port(scheme_)) kc::strprintf(&expr, ":%d", port_);
}
}
kc::strprintf(&expr, "%s", path_.c_str());
if (!query_.empty()) kc::strprintf(&expr, "?%s", query_.c_str());
if (!fragment_.empty()) kc::strprintf(&expr, "#%s", fragment_.c_str());
return expr;
}
/**
* Get the path and the query string for HTTP request.
* @return the path and the query string for HTTP request.
*/
std::string path_query() {
_assert_(true);
return path_ + (query_.empty() ? "" : "?") + query_;
}
/**
* Get the scheme.
* @return the scheme.
*/
std::string scheme() {
_assert_(true);
return scheme_;
}
/**
* Get the host name.
* @return the host name.
*/
std::string host() {
_assert_(true);
return host_;
}
/**
* Get the port number.
* @return the port number.
*/
int32_t port() {
_assert_(true);
return port_;
}
/**
* Get the authority information.
* @return the authority information.
*/
std::string authority() {
_assert_(true);
return authority_;
}
/**
* Get the path.
* @return the path.
*/
std::string path() {
_assert_(true);
return path_;
}
/**
* Get the query string.
* @return the query string.
*/
std::string query() {
_assert_(true);
return query_;
}
/**
* Get the fragment string.
* @return the fragment string.
*/
std::string fragment() {
_assert_(true);
return fragment_;
}
/**
* Assignment operator from the self type.
* @param right the right operand.
* @return the reference to itself.
*/
URL& operator =(const URL& right) {
_assert_(true);
if (&right == this) return *this;
scheme_ = right.scheme_;
host_ = right.host_;
port_ = right.port_;
authority_ = right.authority_;
path_ = right.path_;
query_ = right.query_;
fragment_ = right.fragment_;
return *this;
}
private:
/**
* Parse a string expression.
* @param expr the string expression.
*/
void parse_expression(const std::string& expr) {
scheme_ = "";
host_ = "";
port_ = 0;
authority_ = "";
path_ = "";
query_ = "";
fragment_ = "";
char* trim = kc::strdup(expr.c_str());
kc::strtrim(trim);
char* rp = trim;
char* norm = new char[std::strlen(trim)*3+1];
char* wp = norm;
while (*rp != '\0') {
if (*rp > 0x20 && *rp < 0x7f) {
*(wp++) = *rp;
} else {
*(wp++) = '%';
int32_t num = *(unsigned char*)rp >> 4;
if (num < 10) {
*(wp++) = '0' + num;
} else {
*(wp++) = 'a' + num - 10;
}
num = *rp & 0x0f;
if (num < 10) {
*(wp++) = '0' + num;
} else {
*(wp++) = 'a' + num - 10;
}
}
rp++;
}
*wp = '\0';
rp = norm;
if (kc::strifwm(rp, "http://")) {
scheme_ = "http";
rp += 7;
} else if (kc::strifwm(rp, "https://")) {
scheme_ = "https";
rp += 8;
} else if (kc::strifwm(rp, "ftp://")) {
scheme_ = "ftp";
rp += 6;
} else if (kc::strifwm(rp, "sftp://")) {
scheme_ = "sftp";
rp += 7;
} else if (kc::strifwm(rp, "ftps://")) {
scheme_ = "ftps";
rp += 7;
} else if (kc::strifwm(rp, "tftp://")) {
scheme_ = "tftp";
rp += 7;
} else if (kc::strifwm(rp, "ldap://")) {
scheme_ = "ldap";
rp += 7;
} else if (kc::strifwm(rp, "ldaps://")) {
scheme_ = "ldaps";
rp += 8;
} else if (kc::strifwm(rp, "file://")) {
scheme_ = "file";
rp += 7;
}
char* ep;
if ((ep = std::strchr(rp, '#')) != NULL) {
fragment_ = ep + 1;
*ep = '\0';
}
if ((ep = std::strchr(rp, '?')) != NULL) {
query_ = ep + 1;
*ep = '\0';
}
if (!scheme_.empty()) {
if ((ep = std::strchr(rp, '/')) != NULL) {
path_ = ep;
*ep = '\0';
} else {
path_ = "/";
}
if ((ep = std::strchr(rp, '@')) != NULL) {
*ep = '\0';
if (rp[0] != '\0') authority_ = rp;
rp = ep + 1;
}
if ((ep = std::strchr(rp, ':')) != NULL) {
if (ep[1] != '\0') port_ = kc::atoi(ep + 1);
*ep = '\0';
}
if (rp[0] != '\0') host_ = rp;
if (port_ < 1) port_ = default_port(scheme_);
} else {
path_ = rp;
}
delete[] norm;
delete[] trim;
}
/**
* Get the default port of a scheme.
* @param scheme the scheme.
*/
int32_t default_port(const std::string& scheme) {
if (scheme == "http") return 80;
if (scheme == "https") return 443;
if (scheme == "ftp") return 21;
if (scheme == "sftp") return 22;
if (scheme == "ftps") return 990;
if (scheme == "tftp") return 69;
if (scheme == "ldap") return 389;
if (scheme == "ldaps") return 636;
return 0;
}
/** The scheme. */
std::string scheme_;
/** The host name. */
std::string host_;
/** The port number. */
int32_t port_;
/** The autority information. */
std::string authority_;
/** The path. */
std::string path_;
/** The query string. */
std::string query_;
/** The fragment string. */
std::string fragment_;
};
/**
* HTTP client.
* @note Although all methods of this class are thread-safe, its instance does not have mutual
* exclusion mechanism. So, multiple threads must not share the same instance and they must use
* their own respective instances.
*/
class HTTPClient {
public:
/** The size for a line buffer. */
static const int32_t LINEBUFSIZ = 8192;
/** The maximum size of received data. */
static const int32_t RECVMAXSIZ = 1 << 28;
/**
* Kinds of HTTP request methods.
*/
enum Method {
MGET, ///< GET
MHEAD, ///< HEAD
MPOST, ///< POST
MPUT, ///< PUT
MDELETE, ///< DELETE
MUNKNOWN ///< unknown
};
/**
* Default constructor.
*/
explicit HTTPClient() : sock_(), host_(""), port_(0) {
_assert_(true);
}
/**
* Destructor.
*/
~HTTPClient() {
_assert_(true);
}
/**
* Open the connection.
* @param host the name or the address of the server. If it is an empty string, the local host
* is specified.
* @param port the port numger of the server.
* @param timeout the timeout of each operation in seconds. If it is not more than 0, no
* timeout is specified.
* @param bool secure if this is to be a secure socket
* @param char* ca path of the ca
* @param char* pk path of the private key
* @param char* cert path of the certificate
* @return true on success, or false on failure.
*/
bool open(const std::string& host = "", int32_t port = 80, double timeout = -1,
bool secure = false, const char* ca = NULL, const char* pk = NULL, const char* cert = NULL) {
_assert_(true);
const std::string& thost = host.empty() ? Socket::get_local_host_name() : host;
const std::string& addr = Socket::get_host_address(thost);
if (addr.empty() || port < 1) return false;
std::string expr;
kc::strprintf(&expr, "%s:%d", addr.c_str(), port);
if (timeout > 0) sock_.set_timeout(timeout);
if (!sock_.open(expr, secure, ca, pk, cert)) return false;
host_ = host;
port_ = port;
return true;
}
/**
* Close the connection.
* @param grace true for graceful shutdown, or false for immediate disconnection.
* @return true on success, or false on failure.
*/
bool close(bool grace = true) {
_assert_(true);
return sock_.close(grace);
}
/**
* Fetch a resource.
* @param pathquery the path and the query string of the resource.
* @param method the kind of the request methods.
* @param resbody a string to contain the entity body of the response. If it is NULL, it is
* ignored.
* @param resheads a string map to contain the headers of the response. If it is NULL, it is
* ignored. Header names are converted into lower cases. The empty key means the
* request-line.
* @param reqbody a string which contains the entity body of the request. If it is NULL, it
* is ignored.
* @param reqheads a string map which contains the headers of the request. If it is NULL, it
* is ignored.
* @return the status code of the response, or -1 on failure.
*/
int32_t fetch(const std::string& pathquery, Method method = MGET,
std::string* resbody = NULL,
std::map<std::string, std::string>* resheads = NULL,
const std::string* reqbody = NULL,
const std::map<std::string, std::string>* reqheads = NULL) {
_assert_(true);
if (resbody) resbody->clear();
if (resheads) resheads->clear();
if (pathquery.empty() || pathquery[0] != '/') {
if (resbody) resbody->append("[invalid URL expression]");
return -1;
}
std::string request;
const char* mstr;
switch (method) {
default: mstr = "GET"; break;
case MHEAD: mstr = "HEAD"; break;
case MPOST: mstr = "POST"; break;
case MPUT: mstr = "PUT"; break;
case MDELETE: mstr = "DELETE"; break;
}
kc::strprintf(&request, "%s %s HTTP/1.1\r\n", mstr, pathquery.c_str());
kc::strprintf(&request, "Host: %s", host_.c_str());
if (port_ != 80) kc::strprintf(&request, ":%d", port_);
kc::strprintf(&request, "\r\n");
if (reqbody) kc::strprintf(&request, "Content-Length: %lld\r\n", (long long)reqbody->size());
if (reqheads) {
std::map<std::string, std::string>::const_iterator it = reqheads->begin();
std::map<std::string, std::string>::const_iterator itend = reqheads->end();
while (it != itend) {
char* name = kc::strdup(it->first.c_str());
char* value = kc::strdup(it->second.c_str());
kc::strnrmspc(name);
kc::strtolower(name);
kc::strnrmspc(value);
if (*name != '\0' && !std::strchr(name, ':') && !std::strchr(name, ' ')) {
strcapitalize(name);
kc::strprintf(&request, "%s: %s\r\n", name, value);
}
delete[] value;
delete[] name;
++it;
}
}
kc::strprintf(&request, "\r\n");
if (reqbody) request.append(*reqbody);
if (!sock_.send(request)) {
if (resbody) resbody->append("[sending data failed]");
return -1;
}
char line[LINEBUFSIZ];
if (!sock_.receive_line(line, sizeof(line))) {
if (resbody) resbody->append("[receiving data failed]");
return -1;
}
if (!kc::strfwm(line, "HTTP/1.1 ") && !kc::strfwm(line, "HTTP/1.0 ")) {
if (resbody) resbody->append("[received data was invalid]");
return -1;
}
const char* rp = line + 9;
int32_t code = kc::atoi(rp);
if (code < 1) {
if (resbody) resbody->append("[invalid status code]");
return -1;
}
if (resheads) (*resheads)[""] = line;
int64_t clen = -1;
bool chunked = false;
while (true) {
if (!sock_.receive_line(line, sizeof(line))) {
resbody->append("[receiving data failed]");
return -1;
}
if (*line == '\0') break;
char* pv = std::strchr(line, ':');
if (pv) {
*(pv++) = '\0';
kc::strnrmspc(line);
kc::strtolower(line);
if (*line != '\0') {
while (*pv == ' ') {
pv++;
}
if (!std::strcmp(line, "content-length")) {
clen = kc::atoi(pv);
} else if (!std::strcmp(line, "transfer-encoding")) {
if (!kc::stricmp(pv, "chunked")) chunked = true;
}
if (resheads) (*resheads)[line] = pv;
}
}
}
if (method != MHEAD && code != 304) {
if (clen >= 0) {
if (clen > RECVMAXSIZ) {
if (resbody) resbody->append("[too large response]");
return -1;
}
char* body = new char[clen];
if (!sock_.receive(body, clen)) {
if (resbody) resbody->append("[receiving data failed]");
delete[] body;
return -1;
}
if (resbody) resbody->append(body, clen);
delete[] body;
} else if (chunked) {
int64_t asiz = LINEBUFSIZ;
char* body = (char*)kc::xmalloc(asiz);
int64_t bsiz = 0;
while (true) {
if (!sock_.receive_line(line, sizeof(line))) {
if (resbody) resbody->append("[receiving data failed]");
kc::xfree(body);
return -1;
}
if (*line == '\0') break;
int64_t csiz = kc::atoih(line);
if (bsiz + csiz > RECVMAXSIZ) {
if (resbody) resbody->append("[too large response]");
kc::xfree(body);
return -1;
}
if (bsiz + csiz > asiz) {
asiz = bsiz * 2 + csiz;
body = (char*)kc::xrealloc(body, asiz);
}
if (csiz > 0 && !sock_.receive(body + bsiz, csiz)) {
if (resbody) resbody->append("[receiving data failed]");
kc::xfree(body);
return -1;
}
if (sock_.receive_byte() != '\r' || sock_.receive_byte() != '\n') {
if (resbody) resbody->append("[invalid chunk]");
kc::xfree(body);
return -1;
}
if (csiz < 1) break;
bsiz += csiz;
}
if (resbody) resbody->append(body, bsiz);
kc::xfree(body);
} else {
int64_t asiz = LINEBUFSIZ;
char* body = (char*)kc::xmalloc(asiz);
int64_t bsiz = 0;
while (true) {
int32_t c = sock_.receive_byte();
if (c < 0) break;
if (bsiz > RECVMAXSIZ - 1) {
if (resbody) resbody->append("[too large response]");
kc::xfree(body);
return -1;
}
if (bsiz + 1 > asiz) {
asiz = bsiz * 2;
body = (char*)kc::xrealloc(body, asiz);
}
body[bsiz++] = c;
}
if (resbody) resbody->append(body, bsiz);
kc::xfree(body);
}
}
return code;
}
/**
* Reveal the internal TCP socket.
* @return the internal TCP socket.
*/
Socket* reveal_core() {
_assert_(true);
return &sock_;
}
/**
* Fetch a resource at once
* @param url the URL of the resource.
* @param method the kind of the request methods.
* @param resbody a string to contain the entity body of the response. If it is NULL, it is
* ignored.
* @param resheads a string map to contain the headers of the response. If it is NULL, it is
* ignored. Header names are converted into lower cases. The empty key means the
* request-line.
* @param reqbody a string which contains the entity body of the request. If it is NULL, it
* is ignored.
* @param reqheads a string map which contains the headers of the request. If it is NULL, it
* is ignored.
* @param timeout the timeout of each operation in seconds. If it is not more than 0, no
* timeout is specified.
* @return the status code of the response, or -1 on failure.
*/
static int32_t fetch_once(const std::string& url, Method method = MGET,
std::string* resbody = NULL,
std::map<std::string, std::string>* resheads = NULL,
const std::string* reqbody = NULL,
const std::map<std::string, std::string>* reqheads = NULL,
double timeout = -1) {
_assert_(true);
URL uo(url);
const std::string& scheme = uo.scheme();
const std::string& host = uo.host();
uint32_t port = uo.port();
if (scheme != "http" || host.empty() || port < 1) {
if (resbody) resbody->append("[invalid URL expression]");
return -1;
}
HTTPClient ua;
if (!ua.open(host, port, timeout)) {
if (resbody) resbody->append("[connection refused]");
return -1;
}
std::map<std::string, std::string> rhtmp;
if (reqheads) rhtmp.insert(reqheads->begin(), reqheads->end());
rhtmp["connection"] = "close";
int32_t code = ua.fetch(uo.path_query(), method, resbody, resheads, reqbody, &rhtmp);
if (!ua.close()) {
if (resbody) {
resbody->clear();
resbody->append("[close failed]");
}
return -1;
}
return code;
}
private:
/** Dummy constructor to forbid the use. */
HTTPClient(const HTTPClient&);
/** Dummy Operator to forbid the use. */
HTTPClient& operator =(const HTTPClient&);
/** The socket of connection. */
Socket sock_;
/** The host name of the server. */
std::string host_;
/** The port number of the server. */
int32_t port_;
};
/**
* HTTP server.
*/
class HTTPServer {
public:
class Logger;
class Worker;
class Session;
private:
class WorkerAdapter;
public:
/**
* Interface to log internal information and errors.
*/
class Logger : public ThreadedServer::Logger {
public:
/**
* Destructor.
*/
virtual ~Logger() {
_assert_(true);
}
};
/**
* Interface to process each request.
*/
class Worker {
public:
/**
* Destructor.
*/
virtual ~Worker() {
_assert_(true);
}
/**
* Process each request.
* @param serv the server.
* @param sess the session with the client.
* @param path the path of the requested resource.
* @param method the kind of the request methods.
* @param reqheads a string map which contains the headers of the request. Header names are
* converted into lower cases. The empty key means the request-line.
* @param reqbody a string which contains the entity body of the request.
* @param resheads a string map to contain the headers of the response.
* @param resbody a string to contain the entity body of the response.
* @param misc a string map which contains miscellaneous information. "url" means the
* absolute URL. "query" means the query string of the URL.
* @return the status code of the response. If it is less than 1, internal server error is
* sent to the client and the connection is closed.
*/
virtual int32_t process(HTTPServer* serv, Session* sess,
const std::string& path, HTTPClient::Method method,
const std::map<std::string, std::string>& reqheads,
const std::string& reqbody,
std::map<std::string, std::string>& resheads,
std::string& resbody,
const std::map<std::string, std::string>& misc) = 0;
/**
* Process each binary request.
* @param serv the server.
* @param sess the session with the client.
* @return true to reuse the session, or false to close the session.
*/
virtual bool process_binary(ThreadedServer* serv, ThreadedServer::Session* sess) {
_assert_(serv && sess);
return false;
}
/**
* Process each idle event.
* @param serv the server.
*/
virtual void process_idle(HTTPServer* serv) {
_assert_(serv);
}
/**
* Process each timer event.
* @param serv the server.
*/
virtual void process_timer(HTTPServer* serv) {
_assert_(serv);
}
/**
* Process the starting event.
* @param serv the server.
*/
virtual void process_start(HTTPServer* serv) {
_assert_(serv);
}
/**
* Process the finishing event.
* @param serv the server.
*/
virtual void process_finish(HTTPServer* serv) {
_assert_(serv);
}
};
/**
* Interface to access each session data.
*/
class Session {
friend class HTTPServer;
public:
/**
* Interface of session local data.
*/
class Data : public ThreadedServer::Session::Data {
public:
/**
* Destructor.
*/
virtual ~Data() {
_assert_(true);
}
};
/**
* Get the ID number of the session.
* @return the ID number of the session.
*/
uint64_t id() {
_assert_(true);
return sess_->id();
}
/**
* Get the ID number of the worker thread.
* @return the ID number of the worker thread. It is from 0 to less than the number of
* worker threads.
*/
uint32_t thread_id() {
_assert_(true);
return sess_->thread_id();
}
/**
* Set the session local data.
* @param data the session local data. If it is NULL, no data is registered.
* @note The registered data is destroyed implicitly when the session object is destroyed or
* this method is called again.
*/
void set_data(Data* data) {
_assert_(true);
sess_->set_data(data);
}
/**
* Get the session local data.
* @return the session local data, or NULL if no data is registered.
*/
Data* data() {
_assert_(true);
return (Data*)sess_->data();
}
/**
* Get the expression of the socket.
* @return the expression of the socket or an empty string on failure.
*/
const std::string expression() {
_assert_(true);
return sess_->expression();
}
private:
/**
* Constructor.
*/
explicit Session(ThreadedServer::Session* sess) : sess_(sess) {
_assert_(true);
}
/**
* Destructor.
*/
virtual ~Session() {
_assert_(true);
}
private:
ThreadedServer::Session* sess_;
};
/**
* Default constructor.
*/
explicit HTTPServer() : threaded_(false), serv_(), name_(), worker_() {
_assert_(true);
}
/**
* Destructor.
*/
~HTTPServer() {
_assert_(true);
}
/**
* Set the network configurations.
* @param expr an expression of the address and the port of the server.
* @param timeout the timeout of each network operation in seconds. If it is not more than 0,
* no timeout is specified.
* @param bool secure if this is to be a secure socket
* @param char* ca path of the ca
* @param char* pk path of the private key
* @param char* cert path of the certificate
* @param name the name of the server. If it is an empty string, the host name is specified.
*/
void set_network(const std::string& expr, double timeout = -1, const std::string& name = "", bool secure = false,
const char* ca = NULL, const char* pk = NULL, const char* cert = NULL) {
_assert_(true);
if (timeout > 0) serv_.set_network(expr, timeout, secure, ca, pk, cert);
if (name.empty()) {
name_ = Socket::get_local_host_name();
if (name.empty()) name_ = "localhost";
const char* rp = std::strrchr(expr.c_str(), ':');
if (rp) {
rp++;
int32_t port = kc::atoi(rp);
if (port > 0 && port != 80 && !std::strchr(rp, '[') && !std::strchr(rp, ']') &&
!std::strchr(rp, '/')) kc::strprintf(&name_, ":%d", port);
}
} else {
name_ = name;
}
}
/**
* Set the logger to process each log message.
* @param logger the logger object.
* @param kinds kinds of logged messages by bitwise-or: Logger::DEBUG for debugging,
* Logger::INFO for normal information, Logger::SYSTEM for system information, and
* Logger::ERROR for fatal error.
*/
void set_logger(Logger* logger, uint32_t kinds = Logger::SYSTEM | Logger::ERROR) {
_assert_(true);
serv_.set_logger(logger, kinds);
}
/**
* Set the worker to process each request.
* @param worker the worker object.
* @param thnum the number of worker threads.
*/
void set_worker(Worker* worker, size_t thnum = 1) {
_assert_(true);
worker_.serv_ = this;
worker_.worker_ = worker;
serv_.set_worker(&worker_, thnum);
}
/**
* Start the service.
* @param threaded whether to start a threaded server.
* @return true on success, or false on failure.
* @note This function blocks until the server stops by the HTTPServer::stop method.
*/
bool start(bool threaded = false) {
_assert_(true);
threaded_ = threaded;
if (threaded_) {
serv_.start();
}
else {
serv_.start_listening();
}
return true;
}
/**
* Stop the service.
* @return true on success, or false on failure.
*/
bool stop() {
_assert_(true);
return serv_.stop();
}
/**
* Finish the service.
* @return true on success, or false on failure.
*/
bool finish() {
_assert_(true);
bool ret = serv_.finish();
if (threaded_) {
serv_.join();
}
return ret;
}
/**
* Log a message.
* @param kind the kind of the event. Logger::DEBUG for debugging, Logger::INFO for normal
* information, Logger::SYSTEM for system information, and Logger::ERROR for fatal error.
* @param format the printf-like format string. The conversion character `%' can be used with
* such flag characters as `s', `d', `o', `u', `x', `X', `c', `e', `E', `f', `g', `G', and `%'.
* @param ... used according to the format string.
*/
void log(Logger::Kind kind, const char* format, ...) {
_assert_(format);
va_list ap;
va_start(ap, format);
serv_.log_v(kind, format, ap);
va_end(ap);
}
/**
* Log a message.
* @note Equal to the original Cursor::set_value method except that the last parameters is
* va_list.
*/
void log_v(Logger::Kind kind, const char* format, va_list ap) {
_assert_(format);
serv_.log_v(kind, format, ap);
}
/**
* Reveal the internal TCP server.
* @return the internal TCP server.
*/
ThreadedServer* reveal_core() {
_assert_(true);
return &serv_;
}
/**
* Get the name of a status code.
* @return the name of a status code.
*/
static const char* status_name(int32_t code) {
_assert_(true);
switch (code) {
case 100: return "Continue";
case 101: return "Switching Protocols";
case 102: return "Processing";
case 200: return "OK";
case 201: return "Created";
case 202: return "Accepted";
case 203: return "Non-Authoritative Information";
case 204: return "No Content";
case 205: return "Reset Content";
case 206: return "Partial Content";