This repository was archived by the owner on Apr 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathHttpServer.hh
622 lines (513 loc) · 12 KB
/
HttpServer.hh
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
/**
* Example HTTP Server
*
* Copyright (C) 2020 Ali Bakhtiar
*
* The MIT License
*
* https://twitter.com/ali_bakhtiar
* https://github.com/alibakhtiar
*/
/**
* Compile:
* Linux:
* g++ example.cc HttpServer.hh -std=c++11 -Wall -pthread -O3 -o example.out
* ./example.out <port>
*
* Windows:
* g++ example.cc HttpServer.hh -std=c++11 -Wall -lwsock32 -O3 -IC:\MinGW\include -o example.exe
* ./example.exe <port>
*
*
* Resources:
* https://linux.die.net/man/7/socket
* http://man7.org/linux/man-pages/man7/socket.7.html
*
* @modefied : 20 January 2020
* @created : 19 January 2020
* @author : Ali Bakhtiar
*/
#ifndef EXAMPLEHTTPSERVER_H
#define EXAMPLEHTTPSERVER_H
#include <iostream> // std::string, std::cout
#include <thread> // std::thread
#include <map> // std::map
#include <functional> // std::function
#include <unistd.h> // close
#include <string.h> // memset, strerror
#ifdef __linux__
#include <netinet/tcp.h> // TCP_NODELAY
#include <arpa/inet.h> // struct in_addr, htons
#else
#include <stdio.h>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#endif
#define _FUNC __PRETTY_FUNCTION__
#define _FILE __FILE__
#define _LINE __LINE__
#define _STRERR strerror(errno)
#define APPERROR(message, func, line)\
fprintf(stderr, "%s, function %s, line %d\n", message, func, line);
#define BACKLOG_SIZE 150
#define RECV_BUFFER_SIZE 2048
#define PARSER_STATE_METHOD 1 // request method (GET, POST...)
#define PARSER_STATE_URL 2 // url path
#define PARSER_STATE_URL_QS 3 // QueryString
#define PARSER_STATE_PROTOCOL 4 // http major version
#define PARSER_STATE_MAJOR 5 // http major version
#define PARSER_STATE_MINOR 6 // http minor version
#define PARSER_STATE_HEADERS 7 // key: value
namespace SimpleHttpServer {
const char *httpStatusMessage(int httpStatusCode);
static ssize_t sendBytes(int sock, const char *buffer, size_t length);
void strtolower(std::string &str);
/********************************************************************************/
/**
* Request
*/
class Request
{
public:
int sock; // Socket
struct sockaddr_in addr; // Socket Address (IP)
bool hasError = false;
// HTTP Params
std::string method = "";
std::string url = "";
std::string queryString = "";
int httpMajorVersion = 0;
int httpMinorVersion = 0;
std::map<std::string, std::string> headers;
/**
* Destructor
*/
virtual ~Request(void)
{
this->method.clear();
this->url.clear();
this->queryString.clear();
this->headers.clear();
}
};
/**
* Response
*/
class Response
{
public:
int sock; // Socket
Request *req; // for http headers
int statusCode = 200;
std::map<std::string, std::string> headers;
std::string body = "";
/**
* Set http header
*/
virtual void header(std::string key, std::string value)
{
this->headers[key] = value;
}
/**
* HTML error page
*/
virtual void errorPage(void)
{
this->header("Content-Type", "text/html");
this->header("Cache-Control", "no-cache, no-store, must-revalidate");
this->body = "<!doctype html><html lang=\"en\">";
this->body += "<head><title>Error</title></head>";
this->body += "<body><h1>Error ";
this->body += std::to_string(this->statusCode);
this->body += "</h1><hr><p>";
this->body += httpStatusMessage(this->statusCode);
this->body += "</p></body></html>";
return;
}
/**
* Send all (header and body)
*/
virtual bool send(void)
{
ssize_t sendLen;
std::string head;
this->headers["Content-Length"] = std::to_string(this->body.length());
this->headers["Conection"] = "close";
head = "HTTP/1.";
head += this->req->httpMinorVersion == 0 ? '0' : '1';
head += " ";
head += std::to_string(this->statusCode);
head += " ";
head += httpStatusMessage(this->statusCode);
head += "\r\n";
for (auto const &h : this->headers) {
head += h.first;
head += ": ";
head += h.second;
head += "\r\n";
}
head += "\r\n";
sendLen = this->write(head.c_str(), head.length());
if (sendLen < 0) {
head.clear();
APPERROR(_STRERR, _FUNC, _LINE);
return false;
}
sendLen = this->write(this->body.c_str(), this->body.length());
if (sendLen < 0) {
head.clear();
APPERROR(_STRERR, _FUNC, _LINE);
return false;
}
head.clear();
return true;
}
/**
* Write to socket
*/
virtual ssize_t write(const char *buffer, size_t length)
{
return sendBytes(this->sock, buffer, length);
}
/**
* Destructor
*/
virtual ~Response(void)
{
this->body.clear();
this->headers.clear();
}
};
/**
* Server
*/
class Server
{
// Request callback
typedef std::function<bool(Request *req, Response *res)> callback_t;
public:
std::string ip = "0.0.0.0";
int port = 5000;
/**
* On request callback
*/
virtual void onRequest(callback_t cb)
{
this->onRequestCallback = cb;
}
// callback function (private)
callback_t onRequestCallback = NULL;
};
/********************************************************************************/
/**
* HTTP request parser
*/
bool httpRequestParse(Request *req, const char *buffer, size_t length)
{
std::string tmp = "";
int state = PARSER_STATE_METHOD;
bool isKey = true;
size_t i;
for (i=0; i<length; ++i)
{
switch (state) {
case PARSER_STATE_METHOD:
if (buffer[i] == ' ') {
req->method = tmp;
state = PARSER_STATE_URL;
tmp = "";
break;
}
tmp += buffer[i];
break;
case PARSER_STATE_URL:
if (buffer[i] == ' ' || buffer[i] == '?') {
req->url = tmp;
state = buffer[i] == '?' ? PARSER_STATE_URL_QS : PARSER_STATE_PROTOCOL;
tmp = "";
continue;
}
// Simple XSS filter
// ascii 34 == "
// ascii 39 == '
if (buffer[i] == '<' || buffer[i] == '>' || buffer[i] == 34 || buffer[i] == 39)
continue;
tmp += buffer[i];
break;
case PARSER_STATE_URL_QS:
if (buffer[i] == ' ') {
req->queryString = tmp;
state = PARSER_STATE_PROTOCOL;
tmp = "";
continue;
}
// Simple XSS filter
// ascii 34 == "
// ascii 39 == '
if (buffer[i] == '<' || buffer[i] == '>' || buffer[i] == 34 || buffer[i] == 39)
continue;
tmp += buffer[i];
break;
case PARSER_STATE_PROTOCOL:
if (buffer[i] == '/') {
if (tmp != "HTTP")
req->hasError = true;
state = PARSER_STATE_MAJOR;
tmp = "";
continue;
}
else {
tmp += buffer[i];
}
break;
case PARSER_STATE_MAJOR:
if (isdigit(buffer[i]) != 0) {
req->httpMajorVersion = (int)buffer[i] - '0';
}
else if (buffer[i] == '.') {
state = PARSER_STATE_MINOR;
}
break;
case PARSER_STATE_MINOR:
if (isdigit(buffer[i]) != 0) {
req->httpMinorVersion = (int)buffer[i] - '0';
}
if (buffer[i] == '\n')
state = PARSER_STATE_HEADERS;
break;
case PARSER_STATE_HEADERS:
if (buffer[i] == '\n') {
isKey = true;
tmp = "";
}
else if (isKey == true && buffer[i] == ':') {
strtolower(tmp);
req->headers[tmp] = "";
isKey = false;
}
else if (isKey == true) {
tmp += buffer[i];
}
else if (isKey == false) {
if (buffer[i] == '\r' || (req->headers[tmp].size() == 0 && buffer[i] == ' '))
continue;
req->headers[tmp] += buffer[i];
}
break;
}
}
tmp.clear();
if (req->httpMajorVersion != 1) {
req->hasError = true;
}
return true;
}
/********************************************************************************/
/**
* Send bytes to client
*/
static ssize_t sendBytes(int sock, const char *buffer, size_t length)
{
ssize_t n = 0;
const char *p = buffer;
while (length > 0) {
n = send(sock, p, length, 0);
if (n < 1)
break;
p += n;
length -= n;
}
return n;
}
/**
* Server request handler
*/
static void serverRequestHandler(Server *server, int sock, struct sockaddr_in clientAddr)
{
bool rc;
Request *req;
Response *res;
char *buffer;
ssize_t recvLen;
// New request
req = new Request;
req->sock = sock;
req->addr = clientAddr;
// New response
res = new Response;
res->sock = sock;
res->req = req;
// Recv buffer
buffer = new char[1+RECV_BUFFER_SIZE];
while (1) {
memset(buffer, '\0', 1+RECV_BUFFER_SIZE);
recvLen = recv(sock, buffer, RECV_BUFFER_SIZE, 0);
if (recvLen == 0) {
break;
}
else if (recvLen < 0) {
APPERROR(_STRERR, _FUNC, _LINE);
break;
}
// Request parser
rc = httpRequestParse(req, buffer, recvLen);
if (rc == false)
break;
if (req->hasError == true) {
res->statusCode = 400;
res->errorPage();
res->send();
break;
}
if (server->onRequestCallback != NULL)
server->onRequestCallback(req, res);
break;
}
close(sock);
delete[] buffer;
buffer = NULL;
delete req;
req = NULL;
delete res;
res = NULL;
return;
}
/**
* Create server
*/
bool createServer(Server *server)
{
int st;
int serverFd;
// Create new TCP socket(int family, int type, int protocol)
#ifdef __linux__
serverFd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#else
WSADATA WSAData;
WSAStartup(MAKEWORD(2,0), &WSAData);
serverFd = socket(AF_INET, SOCK_STREAM, 0);
#endif
if (serverFd < 0) {
APPERROR(_STRERR, _FUNC, _LINE);
return false;
}
// Socket options
#ifdef __linux__
int optVal = 1;
// Re use address
st = setsockopt(serverFd, SOL_SOCKET, SO_REUSEADDR, (void *)&optVal, sizeof(int));
if (st == -1) {
APPERROR(_STRERR, _FUNC, _LINE);
return false;
}
// No-delay
st = setsockopt(serverFd, IPPROTO_TCP, TCP_NODELAY, (void *)&optVal, sizeof(int));
if (st == -1) {
APPERROR(_STRERR, _FUNC, _LINE);
return false;
}
#else
bool bOptVal = true;
// No-delay
int iResult = setsockopt(serverFd, SOL_SOCKET, SO_REUSEADDR, (char *)&bOptVal, sizeof(bool));
if (iResult == SOCKET_ERROR) {
APPERROR(_STRERR, _FUNC, _LINE);
return 1;
}
#endif
// Bind
struct sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(struct sockaddr_in));
sockAddr.sin_family = AF_INET;
sockAddr.sin_addr.s_addr = inet_addr((char *)server->ip.c_str());
sockAddr.sin_port = htons(server->port);
st = bind(serverFd, (struct sockaddr *)&sockAddr, sizeof(struct sockaddr_in));
if (st == -1) {
APPERROR(_STRERR, _FUNC, _LINE);
return false;
}
// Listen
st = listen(serverFd, BACKLOG_SIZE);
if (st < 0) {
APPERROR(_STRERR, _FUNC, _LINE);
return false;
}
// Run (main loop)
int clientFd;
struct sockaddr_in clientAddr;
socklen_t clientLength;
clientLength = (socklen_t)sizeof(struct sockaddr_in);
memset(&clientAddr, 0, sizeof(struct sockaddr_in));
std::cout << "http://" <<
server->ip << ":" << server->port << std::endl;
while (1) {
// Accept new connection (new socket)
clientFd = accept(serverFd, (struct sockaddr *)&clientAddr, &clientLength);
if (clientFd <= 0) {
continue;
}
// New thread per connection
#ifdef __linux__
std::thread(serverRequestHandler, server, std::move(clientFd), std::move(clientAddr)).detach();
#else
serverRequestHandler(server, clientFd, clientAddr);
#endif
}
close(serverFd);
#ifndef __linux__
WSACleanup();
#endif
return true;
}
/**
* Http status message
*/
const char *httpStatusMessage(int httpStatusCode)
{
int i;
static const struct {
int httpStatusCode;
const char *message;
} msg[] = {
{200, "Ok"},
{301, "Moved Permanently"},
{302, "Found"},
{304, "Not Modified"},
{307, "Temporary Redirect"},
{400, "Bad Request"},
{401, "Unauthorized"},
{403, "Forbidden"},
{404, "Not Found"},
{405, "Method Not Allowed"},
{411, "Length Required"},
{413, "Request Entity Too Large"},
{414, "Request-URI Too Long"},
{429, "Too Many Requests"},
{500, "Internal Server Error"},
{502, "Bad Gateway"},
{503, "Service Unavailable"},
{504, "Gateway Timeout"},
{505, "HTTP Version Not Supported"},
{0, NULL}
};
for (i=0; msg[i].httpStatusCode != 0; ++i) {
if (msg[i].httpStatusCode == httpStatusCode)
return msg[i].message;
}
return NULL;
}
/**
* Convert a string to lowercase
*/
void strtolower(std::string &str)
{
for (std::string::size_type i=0; i < str.size(); ++i) {
if ((str[i] >= 'A') && (str[i] <= 'Z'))
str[i] += 32;
}
return;
}
} // namespace SimpleHttpServer
#endif // EXAMPLEHTTPSERVER_H