-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathHTTPserver.cpp
652 lines (561 loc) · 18.8 KB
/
HTTPserver.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
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
/*
Arduino tiny web server.
Copyright 2015 Nick Gammon.
Version: 1.3
Change history
--------------
1.1 - Fixed header values to not be percent-encoded, fixed cookie issues.
Also various bugfixes.
1.2 - Added buffering of writes.
1.3 - Removed trailing space from header and cookie values
http://www.gammon.com.au/forum/?id=12942
PERMISSION TO DISTRIBUTE
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
LIMITATION OF LIABILITY
The software is provided "as is", without warranty of any kind, express or implied,
including but not limited to the warranties of merchantability, fitness for a particular
purpose and noninfringement. In no event shall the authors or copyright holders be liable
for any claim, damages or other liability, whether in an action of contract,
tort or otherwise, arising from, out of or in connection with the software
or the use or other dealings in the software.
*/
#include <Arduino.h>
#include <HTTPserver.h>
// ---------------------------------------------------------------------------
// clear the key/value buffers ready for a new key/value
// ---------------------------------------------------------------------------
void HTTPserver::clearBuffers ()
{
keyBuffer [0] = 0;
valueBuffer [0] = 0;
keyBufferPos = 0;
valueBufferPos = 0;
bodyBufferPos = 0;
encodePhase = ENCODE_NONE;
flags = FLAG_NONE;
} // end of HTTPserver::clearBuffers
// ---------------------------------------------------------------------------
// switch states (could add state-change debugging in here)
// ---------------------------------------------------------------------------
void HTTPserver::newState (StateType what)
{
state = what;
} // end of HTTPserver::newState
// ---------------------------------------------------------------------------
// add a character to the key buffer - straight text
// ---------------------------------------------------------------------------
void HTTPserver::addToKeyBuffer (const byte inByte)
{
if (keyBufferPos >= MAX_KEY_LENGTH)
{
flags |= FLAG_KEY_BUFFER_OVERFLOW;
return;
} // end of overflow
keyBuffer [keyBufferPos++] = inByte;
keyBuffer [keyBufferPos] = 0; // trailing null-terminator
} // end of HTTPserver::addToKeyBuffer
// ---------------------------------------------------------------------------
// add a character to the value buffer - percent-encoded (if wanted)
// ---------------------------------------------------------------------------
void HTTPserver::addToValueBuffer (byte inByte, const bool percentEncoded)
{
if (valueBufferPos >= MAX_VALUE_LENGTH)
{
flags |= FLAG_VALUE_BUFFER_OVERFLOW;
return;
} // end of overflow
// look for stuff like "foo+bar" (turn the "+" into a space)
// and also "foo%21bar" (turn %21 into one character)
if (percentEncoded)
{
switch (encodePhase)
{
// if in "normal" mode, turn a "+" into a space, and look for "%"
case ENCODE_NONE:
if (inByte == '+')
inByte = ' ';
else if (inByte == '%')
{
encodePhase = ENCODE_GOT_PERCENT;
return; // no addition to buffer yet
}
break;
// we had the "%" last time, this should be the first hex digit
case ENCODE_GOT_PERCENT:
if (isxdigit (inByte))
{
byte c = toupper (inByte) - '0';
if (c > 9)
c -= 7; // Fix A-F
encodeByte = c << 4;
encodePhase = ENCODE_GOT_FIRST_CHAR;
return; // no addition to buffer yet
}
// not a hex digit, give up
encodePhase = ENCODE_NONE;
flags |= FLAG_ENCODING_ERROR;
break;
// this should be the second hex digit
case ENCODE_GOT_FIRST_CHAR:
if (isxdigit (inByte))
{
byte c = toupper (inByte) - '0';
if (c > 9)
c -= 7; // Fix A-F
inByte = encodeByte | c;
}
else
flags |= FLAG_ENCODING_ERROR;
// done with encoding it, or not a hex digit
encodePhase = ENCODE_NONE;
} // end of switch on encodePhase
} // end of percent-encoded
// add to value buffer, encoding has been dealt with
valueBuffer [valueBufferPos++] = inByte;
valueBuffer [valueBufferPos] = 0; // trailing null-terminator
} // end of HTTPserver::addToValueBuffer
// ---------------------------------------------------------------------------
// add a character to the body buffer - raw binary
// ---------------------------------------------------------------------------
void HTTPserver::addToBodyBuffer (const byte inByte)
{
if (bodyBufferPos >= BODY_CHUNK_LENGTH)
{
// pass current chunk to the application and empty it
processBodyChunk (bodyBuffer, bodyBufferPos, flags);
bodyBufferPos = 0;
} // end of overflow
bodyBuffer [bodyBufferPos++] = inByte;
} // end of HTTPserver::addToBodyBuffer
// ---------------------------------------------------------------------------
// handleSpace - we have an incoming space
// ---------------------------------------------------------------------------
// in the state machine handlers the symbols { } indicate where we think we are
void HTTPserver::handleSpace ()
{
switch (state)
{
// GET{ }/pathname/filename?foo=bar&fubar=true HTTP/1.1
case SKIP_GET_SPACES_1:
// GET /pathname/filename?foo=bar&fubar=true{ }HTTP/1.1
case SKIP_GET_SPACES_2:
// GET /pathname/filename?foo=bar&fubar=true HTTP/1.1{ }
case SKIP_TO_END_OF_LINE:
// Cookie:{ }foo=bar;
case SKIP_COOKIE_SPACES:
break; // ignore these spaces
// GET{ }/pathname/filename?foo=bar&fubar=true HTTP/1.1
case GET_LINE:
processPostType (keyBuffer, flags);
// see if it is a POST type
postRequest = strcmp (keyBuffer, "POST") == 0;
newState (SKIP_GET_SPACES_1);
clearBuffers ();
break;
// GET /pathname/filename?foo=bar&fubar=true{ }HTTP/1.1
case GET_PATHNAME:
processPathname (valueBuffer, flags);
newState (SKIP_GET_SPACES_2);
clearBuffers ();
break;
// GET /pathname/filename?foo=bar&fubar=true{ }HTTP/1.1
case GET_ARGUMENT_NAME:
processGetArgument (keyBuffer, valueBuffer, flags);
newState (SKIP_GET_SPACES_2);
clearBuffers ();
break;
// GET /pathname/filename?foo{ }HTTP/1.1
case GET_ARGUMENT_VALUE:
processGetArgument (keyBuffer, valueBuffer, flags);
newState (SKIP_GET_SPACES_2);
clearBuffers ();
break;
// GET /pathname/filename?foo=bar&fubar=true HTTP/1.1{ }
case GET_HTTP_VERSION:
processHttpVersion (keyBuffer, flags);
newState (SKIP_TO_END_OF_LINE);
clearBuffers ();
break;
// Accept-Encoding: gzip,{ }deflat
case HEADER_VALUE:
case COOKIE_VALUE:
addToValueBuffer (' ', false);
break;
// Accept-Encoding{ }:
// space shouldn't be there, but we'll ignore it
case HEADER_NAME:
break;
default:
break; // do nothing
} // end of switch on state
} // end of HTTPserver::handleSpace
// ---------------------------------------------------------------------------
// handleNewline - we have an incoming newline
// ---------------------------------------------------------------------------
void HTTPserver::handleNewline ()
{
// pretend there was a trailing space and wrap up the previous line
if (state != SKIP_TO_END_OF_LINE &&
state != SKIP_INITIAL_LINES &&
state != HEADER_VALUE && // don't have trailing space on header value
state != COOKIE_VALUE) // nor on cookie value
handleSpace ();
switch (state)
{
// default is the start of a new header line
default:
clearBuffers ();
newState (START_LINE);
break;
// ignore blank lines before the GET/POST line
case SKIP_INITIAL_LINES:
break;
// a blank line on its own signals switching to the POST key/values or binary body
case START_LINE:
clearBuffers ();
newState (binaryBody ? BODY : POST_NAME);
break;
// wrap up this POST key/value and start a new one
case POST_NAME:
case POST_VALUE:
if (keyBufferPos > 0)
processPostArgument (keyBuffer, valueBuffer, flags);
newState (POST_NAME);
clearBuffers ();
break;
// end of a header value, start looking for a new header
case HEADER_VALUE:
processHeaderArgument (keyBuffer, valueBuffer, flags);
// remember the content length for the POST data
if (strcasecmp (keyBuffer, "Content-Length") == 0)
contentLength = atol (valueBuffer);
if (strcasecmp (keyBuffer, "Content-Type") == 0 && strcasecmp (valueBuffer, "application/octet-stream") == 0)
binaryBody = true;
clearBuffers ();
newState (START_LINE);
break;
case COOKIE_VALUE:
processCookie (keyBuffer, valueBuffer, flags);
newState (START_LINE);
clearBuffers ();
break;
} // end of switch on state
} // end of HTTPserver::handleNewline
// ---------------------------------------------------------------------------
// handleText - we have an incoming character other than a space or newline
// ---------------------------------------------------------------------------
// in the state machine handlers the symbols { } indicate where we think we are
void HTTPserver::handleText (const byte inByte)
{
switch (state)
{
// blank lines before GET line
case SKIP_INITIAL_LINES:
newState (GET_LINE);
addToKeyBuffer (inByte);
break;
// {GET} /whatever/foo.htm HTTP/1.1
case GET_LINE:
// GET /whatever/foo.htm {HTTP/1.1}
case GET_HTTP_VERSION:
addToKeyBuffer (inByte);
break;
// {Connection}: keep-alive
case HEADER_NAME:
if (inByte == ':')
{
if (strcasecmp (keyBuffer, "Cookie") == 0)
{
newState (SKIP_COOKIE_SPACES);
clearBuffers ();
}
else
newState (SKIP_HEADER_SPACES);
}
else
addToKeyBuffer (inByte);
break;
// Connection: {k}eep-alive
case SKIP_HEADER_SPACES:
newState (HEADER_VALUE);
addToValueBuffer (inByte, false);
break;
// Connection: {keep-alive}
case HEADER_VALUE:
addToValueBuffer (inByte, false);
break;
// Cookie: foo=bar;{ }whatever=something;
case SKIP_COOKIE_SPACES:
newState (COOKIE_NAME);
addToKeyBuffer (inByte);
break;
// Cookie: {foo}=bar;
case COOKIE_NAME:
if (inByte == '=')
newState (COOKIE_VALUE);
else
addToKeyBuffer (inByte);
break;
// Cookie: foo={bar};
case COOKIE_VALUE:
if (inByte == ';' || inByte == ',')
{
processCookie (keyBuffer, valueBuffer, flags);
newState (SKIP_COOKIE_SPACES);
clearBuffers ();
}
else
addToValueBuffer (inByte, false);
break;
// {foo}=bar&answer=42
case POST_NAME:
if (inByte == '&')
{
processPostArgument (keyBuffer, valueBuffer, flags);
newState (POST_NAME);
clearBuffers ();
}
else if (inByte == '=')
newState (POST_VALUE);
else
addToKeyBuffer (inByte);
break;
// foo={bar}&answer=42
case POST_VALUE:
if (inByte == '&')
{
processPostArgument (keyBuffer, valueBuffer, flags);
newState (POST_NAME);
clearBuffers ();
}
else
addToValueBuffer (inByte, true);
break;
// GET {/whatever/foo.htm} HTTP/1.1
case SKIP_GET_SPACES_1:
newState (GET_PATHNAME);
addToValueBuffer (inByte, true);
break;
// GET /pathname/filename?{foo}=bar&fubar=true
case GET_ARGUMENT_NAME:
if (inByte == '&')
{
processGetArgument (keyBuffer, valueBuffer, flags);
newState (GET_ARGUMENT_NAME);
clearBuffers ();
}
else if (inByte == '=')
newState (GET_ARGUMENT_VALUE);
else
addToKeyBuffer (inByte);
break;
// GET /pathname/filename?foo={bar}&fubar=true
case GET_ARGUMENT_VALUE:
if (inByte == '&')
{
processGetArgument (keyBuffer, valueBuffer, flags);
newState (GET_ARGUMENT_NAME);
clearBuffers ();
}
else
addToValueBuffer (inByte, true);
break;
// GET {/pathname/filename}?foo=bar&fubar=true
case GET_PATHNAME:
if (inByte == '?')
{
processPathname (valueBuffer, flags);
newState (GET_ARGUMENT_NAME);
clearBuffers ();
}
else
addToValueBuffer (inByte, true);
break;
// GET /whatever/foo.htm {HTTP/1.1}
case SKIP_GET_SPACES_2:
newState (GET_HTTP_VERSION);
addToKeyBuffer (inByte);
break;
// {C}onnection: keep-alive
case START_LINE:
newState (HEADER_NAME);
addToKeyBuffer (inByte);
break;
// we think line is done, skip whatever we find
case SKIP_TO_END_OF_LINE:
break; // ignore it
} // end of switch on state
} // end of HTTPserver::handleText
// ---------------------------------------------------------------------------
// processIncomingByte - our main sketch has received a byte from the client
// ---------------------------------------------------------------------------
void HTTPserver::processIncomingByte (const byte inByte)
{
// count received bytes in POST section or binary body
if (state == POST_NAME || state == POST_VALUE || state == BODY)
receivedLength++;
if (state == BODY)
{
addToBodyBuffer (inByte);
// if all received, stop now
if (receivedLength >= contentLength)
{
// wrap up last partial binary chunk (always at least 1 byte here by definition)
processBodyChunk (bodyBuffer, bodyBufferPos, flags);
clearBuffers ();
done = true;
}
// don't process data specially inside a binary body
return;
}
switch (inByte)
{
case '\r':
break; // ignore carriage-return
case ' ':
case '\t':
handleSpace (); // generally switches states
break;
case '\n':
handleNewline (); // generally switches states
break;
default:
handleText (inByte); // collect text
break;
} // end of switch on inByte
// see if count of content bytes is up
if (state == POST_NAME || state == POST_VALUE)
{
// if all received, stop now
if (receivedLength >= contentLength)
{
// handle final POST item
if (keyBufferPos > 0)
handleNewline ();
done = true;
return;
} // end of Content-Length reached
// not a POST request? don't look for more data
if (!postRequest)
done = true;
} // end of up to the POST states
} // end of HTTPserver::processIncomingByte
// ---------------------------------------------------------------------------
// begin - reset state machine to the start
// ---------------------------------------------------------------------------
void HTTPserver::begin (Print * output_)
{
// reset everything to initial state
state = SKIP_INITIAL_LINES;
encodePhase = ENCODE_NONE;
flags = FLAG_NONE;
postRequest = false;
binaryBody = false;
contentLength = 0;
receivedLength = 0;
sendBufferPos = 0;
output = output_;
clearBuffers ();
done = false;
} // end of HTTPserver::begin
// ---------------------------------------------------------------------------
// write - for outputting via print, println etc.
// ---------------------------------------------------------------------------
size_t HTTPserver::write (uint8_t c)
{
// forget it, if they supplied no output device
if (!output)
return 0;
// only buffer writes up, if a non-zero buffer length
if (SEND_BUFFER_LENGTH > 0)
{
sendBuffer [sendBufferPos++] = c;
// if full, flush it
if (sendBufferPos >= SEND_BUFFER_LENGTH)
flush ();
}
else
output->write (c); // otherwise write a byte at a time
return 1;
} // end of HTTPserver::write
void HTTPserver::flush ()
{
if (sendBufferPos > 0)
{
output->write (sendBuffer, sendBufferPos);
sendBufferPos = 0;
} // end of anything in buffer
} // end of HTTPserver::flush
// ---------------------------------------------------------------------------
// fixHTML - convert special characters such as < > and &
// ---------------------------------------------------------------------------
void HTTPserver::fixHTML (const char * message)
{
char c;
while ((c = *message++))
{
switch (c)
{
case '<': print ("<"); break;
case '>': print (">"); break;
case '&': print ("&"); break;
case '"': print ("""); break;
default: write (c); break;
} // end of switch
} // end of while
} // end of HTTPserver::fixHTML
// ---------------------------------------------------------------------------
// urlEncode - convert special characters such as spaces into percent-encoded
// ---------------------------------------------------------------------------
void HTTPserver::urlEncode (const char * message)
{
char c;
while ((c = *message++))
{
if (!isalpha (c) && !isdigit(c))
{
// compact conversion to hex
write ('%');
char x = ((c >> 4) & 0xF) | '0';
if (x > '9')
x += 7;
write (x);
x = (c & 0xF) | '0';
if (x > '9')
x += 7;
write (x);
}
else
write (c);
} // end of while
} // end of HTTPserver::urlEncode
// ---------------------------------------------------------------------------
// setCookie - cookies only permit certain characters
// ---------------------------------------------------------------------------
void HTTPserver::setCookie (const char * name, const char * value, const char * extra)
{
print (F("Set-Cookie: "));
// send the name which excludes spaces, ';', ',' or '='
for (const char * p = name; *p; p++)
if (*p >= '!' && *p <= '~' && *p != ';' && *p != ';' && *p != '=')
write (*p);
write ('=');
// send the value which excludes ';' or ','
for (const char * p = value; *p; p++)
if (*p >= ' ' && *p <= '~' && *p != ';' && *p != ';')
write (*p);
// terminate value with semicolon and space
print (F("; "));
// extra stuff like:
// Path=/accounts; Expires=Wed, 13 Jan 2021 22:23:01 GMT; Secure; HttpOnly
if (extra)
print (extra);
// end of header line
println ();
} // end of HTTPserver::setCookie