-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.cpp
543 lines (455 loc) · 13.9 KB
/
webserver.cpp
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
#include "webserver.hpp"
#include "webapp404.hpp"
static BlockPool blockPool; // big lump of static memory to allocate from.
static Webapp404 webapp404; // default to generate 404 not found.
////////////////////////////////////////////////////////////////////
// Parameter
/// @brief Convenience method to return value as an int.
/// @return value as an int.
int Parameter::asInt(){
return atoi(_value);
}
/// @brief Convenience method to get a RGB colour.
/// @return RGB colour as uint32_t.
uint32_t Parameter::asRgb(){
//long int strtol (const char* str, char** endptr, int base);
const char* pos = _value;
if(*pos == '#') ++pos;
return strtol(pos, 0, 16);
}
/// @brief Convenience method to get value as a float.
/// @return value as a float.
float Parameter::asFloat(){
return atof(_value);
}
////////////////////////////////////////////////////////////////////
// Header
// Build up a string ready for transmission.
const char* Header::toSend(Block* block){
int size = strlen(_name) + strlen(_value) + 5; // +5 for: CR LF : <sp> 0
char* buffer = (char*)block->allocate(size);
char* there = buffer;
const char* here = _name;
while(*here){
*there++ = *here++;
}
*there++ = ':';
*there++ = ' ';
here = _value;
while(*here){
*there++ = *here++;
}
*there++ = '\r';
*there++ = '\n';
*there = 0;
printf("Header toSend:%s\n",buffer);
return buffer;
}
////////////////////////////////////////////////////////////////////
// Convert 2 hex digits into a character for URL decode
static char decode(char msHex, char lsHex){
const char* digits = "0123456789ABCDEF";
int val='?';
if(msHex >= 'a' && msHex <= 'f') val = (msHex - 'a' + 10) * 16;
else if(msHex >= 'A' && msHex <= 'F') val = (msHex - 'A' + 10) * 16;
else if(msHex >= '0' && msHex <= '9') val = (msHex - '0') * 16;
if(lsHex >= 'a' && lsHex <= 'f') val += (lsHex - 'a' + 10);
else if(lsHex >= 'A' && lsHex <= 'F') val += (lsHex - 'A' + 10);
else if(lsHex >= '0' && lsHex <= '9') val += (lsHex - '0');
return (char)val;
}
HttpRequest::HttpRequest(Block* block)
: block(block)
, _complete(false)
, _verb(0)
, _path(0)
, _protocol(0)
, _body(0)
, parseMessage(0)
{
}
HttpRequest::~HttpRequest(){
}
int HttpRequest::parseInitialLine(char*& here, char*& there, int length) {
// First, the HTTP verb - GET, POST etc.
this->_verb = there;
while(length > 0 && !isspace(*here)){
*there++ = *here++;
--length;
}
*there++ = 0;
// Skip spaces
while(length > 0 && isspace(*here)){
++here; --length;
}
// Get path expression
this->_path = there;
char* query = 0;
while(!isspace(*here) && length){
if(*here == '%' && length > 2) { // URL encoded
++here; // skip %
char msHex = *here++;
char lsHex = *here++;
length -= 3;
*there++ = decode(msHex, lsHex);
} else if (*here == '?'){ // start of query string.
++here; // skip '?'
--length;
query = here;
break; // go into next loop to parse query string
} else { // Just normal char in
*there++ = *here++;
--length;
}
}
*there++ = 0; // terminate path;
if(query){
char* key = there;
char* value = 0;
while(!isspace(*here) && length){
if(*here == '%' && length > 2) { // URL encoded
++here; // skip %
char msHex = *here++;
char lsHex = *here++;
length -= 3;
*there++ = decode(msHex, lsHex);
} else if (*here == '=' && length){ // start of value
++here;
*there++ = 0;
--length;
value = there;
} else if (*here == '&' && length){ // start of another param.
++here; // skip &
*there++ = 0;
--length;
Parameter* p = new(block) Parameter(key, value);
this->_Parameters.add(block, p);
key = there; // start of new key
value = 0;
} else {
*there++ = *here++;
--length;
}
}
*there++ = 0; // terminate last value
// Process last key/value pair
Parameter* p = new(block) Parameter(key, value);
this->_Parameters.add(block, p);
}
// skip spaces
if(length > 0 && isspace(*here)){
++here; --length;
}
// here should now point to HTTP/1.1
// Can optionally validate, get version etc.
// Copy until CRLF skipping any spaces.
this->_protocol = there;
while(length){
if(*here == '\r') {
++here; --length;
} else if(*here == '\n') {
++here; --length;
break;
} else if(isspace(*here)){
++here; --length;
} else {
*there++ = *here++;
--length;
}
}
*there++ = 0;
// Ok, so the first line should be parsed!
printf("verb: %s\n", _verb);
printf("path: %s\n", _path);
printf("protocol: %s\n", _protocol);
return length;
}
/// @brief Parses a single header line of an HTTP request.
/// e.g.:
/// Accept-Encoding: gzip, deflate
/// Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
/// @param here
/// @param there
/// @param length
/// @return
int HttpRequest::parseHeaderLine(char*& here, char*& there, int length){
if(length == 0) return 0;
char*key = there;
char*val = 0;
while(length){
if(*here == ':'){
++here; --length; // skip :
break;
} else {
*there++ = *here++;
--length;
}
}
*there++ = 0; // terminate key
// Skip space(s)
while(length && isspace(*here)) {
++here; --length;
}
// Copy value until CRLF
if(length){
val = there;
while(length && *here!='\r' && *here!='\n'){
*there++ = *here++;
--length;
}
*there++ = 0;
}
if(key && val) {
Header* header = new(block) Header(key, val);
this->_headers.add(block, header);
}
// Skip over trailing CRLF
while(length && (*here == '\r' || *here == '\n')){
++here; --length;
}
return length;
}
/// @brief Parses the body of the HTTP request.
/// @param here
/// @param there
/// @param length
/// @return
int HttpRequest::parseBody(char*& here, char*& there, int length){
if(length){
_body = there;
while(length) {
*there++ = *here++;
--length;
}
*there = 0;
}
return length;
}
// GET /set?brt=43&rgb=%23ff38d4 HTTP/1.1
// GET /wonky%20donkey HTTP/1.1
void HttpRequest::parse(void* data, uint16_t length){
// Total size of strings from request (including nulls)
// will always be less or equal to the size of the request.
// Each string has a delimiter in the request and some may
// shrink due to URL encoding.
char* there = (char*)block->allocate(length);
if(there == 0){
parseMessage = "HTTP/1.1 500 Internal Server Error\r\n";
return;
}
// Now copy data from here to there, adding delimiters as
// necessary and noting where the fields are.
char* here = (char*)data;
length = parseInitialLine(here, there, length);
// Look for headers - terminate on CRLF.
while(length > 0 && *here != '\r' && *here != '\n'){
length = parseHeaderLine(here, there, length);
}
// Skip over any CRLF.
while((length > 0) && (*here == '\r' || *here =='\n')){
++here; --length;
}
length = parseBody(here, there, length);
_complete = true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// HttpResponse
HttpResponse::HttpResponse(Block* block)
: block(block)
, statusCode(200)
, statusMsg("OK")
, body(0)
{}
void HttpResponse::setStatus(int code, const char* msg){
statusCode = code;
statusMsg = msg;
}
void HttpResponse::addHeader(const char* key, const char* value){
Header* h = new(block) Header(key, value);
_headers.add(block, h);
}
void HttpResponse::setBody(const char* payload){
this->body = payload;
}
const char* HttpResponse::protocolLine(){
const char* p = "HTTP/1.1 ";
size_t len = strlen(p) + 3 + 1 + strlen(statusMsg) + 1;
char* buff = (char*) block->allocate(len);
if(buff) {
char* there = buff;
const char* here = p;
while(*here){
*there++ = *here++;
}
if(statusCode > 999) statusCode = 999; // 3 digits
itoa(statusCode, there, 10 );
while(*there) ++there; //Find trailing zero
*there++ = ' ';
here = statusMsg;
while(*here){
*there++ = *here++;
}
*there++ = '\r';
*there++ = '\n';
*there++ = 0;
}
printf("Protocol line:%s\n", buff);
return buff;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// HttpTransaction
HttpTransaction::HttpTransaction(Block* block)
: _block(block)
, _request(block)
, _response(block){
assert(block);
}
HttpTransaction::~HttpTransaction(){
}
void* HttpTransaction::operator new(size_t size, Block* block){
return block->allocate(size);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
Webserver::Webserver()
:appCount(0)
{
for(int i=0; i<MAX_APPS; ++i){
apps[i] = 0;
}
}
void Webserver::connected(Connection* connection){
printf("connected\n");
connection->setAppState(0); // no existing transaction as new connection
}
void Webserver::closed(Connection* connection){
printf("closed\n");
HttpTransaction* tx = (HttpTransaction*)connection->getAppState();
if(tx) {
Block* block = tx->getBlock();
block->free();
connection->setAppState(0);
}
}
// GET /hello.txt HTTP/1.1
//
// HTTP/1.1 200 OK
// Date: Mon, 27 Jul 2009 12:28:53 GMT
// Server: Apache
// Content-Length: 51
//
// Some content here
err_t Webserver::receive(Connection* connection, void* data, uint16_t length){
printf("Received %d ======================\n",length);
char* text = (char*)data;
for(int i=0; i<length; ++i){
putchar(text[i]);
}
printf("==================================\n");
// check for existing transaction
HttpTransaction* tx = static_cast<HttpTransaction*>(connection->getAppState());
if(tx == 0){
Block* block = blockPool.allocate();
if(block == 0){
printf("No memory to handle request");
const char* header = "HTTP/1.1 500 No memory\r\n";
connection->send((uint8_t*)header, strlen(header));
return ERR_OK;
}
printf("Create transaction\n");
tx = new(block) HttpTransaction(block);
connection->setAppState(tx);
printf("Parsing request\n");
tx->request().parse(data, length);
} else {
// There's an existing request and some more data here.
}
// bail out if request parsing failed.
const char* fail = tx->request().failureMessage();
if(fail){
connection->send((uint8_t*)fail, strlen(fail));
return ERR_OK;
}
// If request is complete then process & send result
if(tx->request().isComplete()){
// Find a webapp to process the request (404 is default)
WebApp* app = &webapp404;
for(int i=0; i<appCount; ++i){
if(apps[i]->matches(tx->request().verb(), tx->request().path())) {
app = apps[i];
break;
}
}
app->process(tx->request(), tx->response());
sendResponse(tx, connection);
}
return ERR_OK;
}
size_t Webserver::sendResponse(HttpTransaction* tx, Connection* connection){
assert(tx);
assert(tx->getBlock());
assert(connection);
size_t bytesToSend = 0;
size_t len;
const char* value = tx->response().protocolLine();
len = strlen(value);
connection->send((uint8_t*)value, len);
bytesToSend += len;
BlockListIter<Header> iter = tx->response().headers().iter();
Header* h;
while( (h = iter.next()) != 0){
value = h->toSend(tx->getBlock());
len = strlen(value);
connection->send((uint8_t*)value, len);
bytesToSend += len;
}
// Blank line after any headers.
value = "\r\n";
len = strlen(value);
connection->send((uint8_t*)value, len);
bytesToSend += len;
// Followed by (optional) body.
value = tx->response().getBody();
if(value){
len = strlen(value);
connection->send((uint8_t*)value, len);
bytesToSend += len;
}
tx->setSendSize(bytesToSend);
return bytesToSend;
}
err_t Webserver::poll(Connection* connection){
return ERR_OK;
}
void Webserver::error(Connection* connection, err_t err){
printf("Error %d\n", err);
HttpTransaction* tx = static_cast<HttpTransaction*>(connection->getAppState());
if(tx){
Block* block = tx->getBlock();
block->free();
connection->setAppState(0);
connection->close(); // if not already.
}
}
err_t Webserver::sent(Connection* connection, u16_t bytesSent){
printf("sent %d\n", bytesSent);
HttpTransaction* tx = static_cast<HttpTransaction*>(connection->getAppState());
if(tx){
tx->sent(bytesSent);
if(tx->sendComplete()){
Block* block = tx->getBlock();
block->free();
connection->setAppState(0);
connection->close();
}
}
return ERR_OK;
}
/// @brief Adds a WebApp to the server.
/// @param app is the app to add.
/// @return true if added, false if no space.
bool Webserver::addApplication(WebApp* app){
assert(app);
if(appCount == MAX_APPS) return false;
apps[appCount++] = app;
return true;
}