-
Notifications
You must be signed in to change notification settings - Fork 1
/
WebServer.h
1161 lines (1007 loc) · 31.8 KB
/
WebServer.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
// Filename: WebServer.h
// Version 1.5 08/19/13 JS MiloCreek
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-file-style: "k&r"; c-basic-offset: 2; -*-
Webduino, a simple Arduino web server
Copyright 2009-2012 Ben Combee, Ran Talbott, Christopher Lee, Martin Lormes
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.
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.
*/
#ifndef WEBDUINO_H_
#define WEBDUINO_H_
#include <string.h>
#include <stdlib.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
/********************************************************************
* CONFIGURATION
********************************************************************/
#define WEBDUINO_VERSION 1007
#define WEBDUINO_VERSION_STRING "1.7"
#if WEBDUINO_SUPRESS_SERVER_HEADER
#define WEBDUINO_SERVER_HEADER ""
#else
#define WEBDUINO_SERVER_HEADER "Server: Webduino/" WEBDUINO_VERSION_STRING CRLF
#endif
// standard END-OF-LINE marker in HTTP
#define CRLF "\r\n"
// If processConnection is called without a buffer, it allocates one
// of 32 bytes
#define WEBDUINO_DEFAULT_REQUEST_LENGTH 32
// How long to wait before considering a connection as dead when
// reading the HTTP request. Used to avoid DOS attacks.
#ifndef WEBDUINO_READ_TIMEOUT_IN_MS
#define WEBDUINO_READ_TIMEOUT_IN_MS 1000
#endif
#ifndef WEBDUINO_FAIL_MESSAGE
#define WEBDUINO_FAIL_MESSAGE "<h1>EPIC FAIL</h1>"
#endif
#ifndef WEBDUINO_AUTH_REALM
#define WEBDUINO_AUTH_REALM "Webduino"
#endif // #ifndef WEBDUINO_AUTH_REALM
#ifndef WEBDUINO_AUTH_MESSAGE
#define WEBDUINO_AUTH_MESSAGE "<h1>401 Unauthorized</h1>"
#endif // #ifndef WEBDUINO_AUTH_MESSAGE
#ifndef WEBDUINO_SERVER_ERROR_MESSAGE
#define WEBDUINO_SERVER_ERROR_MESSAGE "<h1>500 Internal Server Error</h1>"
#endif // WEBDUINO_SERVER_ERROR_MESSAGE
// add '#define WEBDUINO_FAVICON_DATA ""' to your application
// before including WebServer.h to send a null file as the favicon.ico file
// otherwise this defaults to a 16x16 px black diode on blue ground
// (or include your own icon if you like)
#ifndef WEBDUINO_FAVICON_DATA
#define WEBDUINO_FAVICON_DATA { 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, \
0x10, 0x02, 0x00, 0x01, 0x00, 0x01, 0x00, \
0xb0, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, \
0x00, 0x28, 0x00, 0x00, 0x00, 0x10, 0x00, \
0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, \
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, \
0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, \
0x00, 0xff, 0xff, 0x00, 0x00, 0xcf, 0xbf, \
0x00, 0x00, 0xc7, 0xbf, 0x00, 0x00, 0xc3, \
0xbf, 0x00, 0x00, 0xc1, 0xbf, 0x00, 0x00, \
0xc0, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0xc0, 0xbf, 0x00, 0x00, 0xc1, 0xbf, \
0x00, 0x00, 0xc3, 0xbf, 0x00, 0x00, 0xc7, \
0xbf, 0x00, 0x00, 0xcf, 0xbf, 0x00, 0x00, \
0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00 }
#endif // #ifndef WEBDUINO_FAVICON_DATA
// add "#define WEBDUINO_SERIAL_DEBUGGING 1" to your application
// before including WebServer.h to have incoming requests logged to
// the serial port.
#ifndef WEBDUINO_SERIAL_DEBUGGING
#define WEBDUINO_SERIAL_DEBUGGING 0
#endif
#if WEBDUINO_SERIAL_DEBUGGING
#include <HardwareSerial.h>
#endif
// declared in wiring.h
extern "C" unsigned long millis(void);
// declare a static string
#define P(name) static const prog_uchar name[] PROGMEM
// returns the number of elements in the array
#define SIZE(array) (sizeof(array) / sizeof(*array))
/********************************************************************
* DECLARATIONS
********************************************************************/
/* Return codes from nextURLparam. NOTE: URLPARAM_EOS is returned
* when you call nextURLparam AFTER the last parameter is read. The
* last actual parameter gets an "OK" return code. */
typedef enum URLPARAM_RESULT { URLPARAM_OK,
URLPARAM_NAME_OFLO,
URLPARAM_VALUE_OFLO,
URLPARAM_BOTH_OFLO,
URLPARAM_EOS // No params left
};
class WebServer: public Print
{
public:
// passed to a command to indicate what kind of request was received
enum ConnectionType { INVALID, GET, HEAD, POST, PUT, DELETE, PATCH };
// any commands registered with the web server have to follow
// this prototype.
// url_tail contains the part of the URL that wasn't matched against
// the registered command table.
// tail_complete is true if the complete URL fit in url_tail, false if
// part of it was lost because the buffer was too small.
typedef void Command(WebServer &server, ConnectionType type,
char *url_tail, bool tail_complete);
// constructor for webserver object
WebServer(const char *urlPrefix = "", int port = 80);
// start listening for connections
void begin();
// check for an incoming connection, and if it exists, process it
// by reading its request and calling the appropriate command
// handler. This version is for compatibility with apps written for
// version 1.1, and allocates the URL "tail" buffer internally.
void processConnection();
// check for an incoming connection, and if it exists, process it
// by reading its request and calling the appropriate command
// handler. This version saves the "tail" of the URL in buff.
void processConnection(char *buff, int *bufflen);
// set command that's run when you access the root of the server
void setDefaultCommand(Command *cmd);
// set command run for undefined pages
void setFailureCommand(Command *cmd);
// add a new command to be run at the URL specified by verb
void addCommand(const char *verb, Command *cmd);
// utility function to output CRLF pair
void printCRLF();
// output a string stored in program memory, usually one defined
// with the P macro
void printP(const prog_uchar *str);
// inline overload for printP to handle signed char strings
void printP(const prog_char *str) { printP((prog_uchar*)str); }
// output raw data stored in program memory
void writeP(const prog_uchar *data, size_t length);
// output HTML for a radio button
void radioButton(const char *name, const char *val,
const char *label, bool selected);
// output HTML for a checkbox
void checkBox(const char *name, const char *val,
const char *label, bool selected);
// returns next character or -1 if we're at end-of-stream
int read();
// put a character that's been read back into the input pool
void push(int ch);
// returns true if the string is next in the stream. Doesn't
// consume any character if false, so can be used to try out
// different expected values.
bool expect(const char *expectedStr);
// returns true if a number, with possible whitespace in front, was
// read from the server stream. number will be set with the new
// value or 0 if nothing was read.
bool readInt(int &number);
// reads a header value, stripped of possible whitespace in front,
// from the server stream
void readHeader(char *value, int valueLen);
// Read the next keyword parameter from the socket. Assumes that other
// code has already skipped over the headers, and the next thing to
// be read will be the start of a keyword.
//
// returns true if we're not at end-of-stream
bool readPOSTparam(char *name, int nameLen, char *value, int valueLen);
// Read the next keyword parameter from the buffer filled by getRequest.
//
// returns 0 if everything weent okay, non-zero if not
// (see the typedef for codes)
URLPARAM_RESULT nextURLparam(char **tail, char *name, int nameLen,
char *value, int valueLen);
// compare string against credentials in current request
//
// authCredentials must be Base64 encoded outside of Webduino
// (I wanted to be easy on the resources)
//
// returns true if strings match, false otherwise
bool checkCredentials(const char authCredentials[45]);
// output headers and a message indicating a server error
void httpFail();
// output headers and a message indicating "401 Unauthorized"
void httpUnauthorized();
// output headers and a message indicating "500 Internal Server Error"
void httpServerError();
// output standard headers indicating "200 Success". You can change the
// type of the data you're outputting or also add extra headers like
// "Refresh: 1". Extra headers should each be terminated with CRLF.
void httpSuccess(const char *contentType = "text/html; charset=utf-8",
const char *extraHeaders = NULL);
// used with POST to output a redirect to another URL. This is
// preferable to outputting HTML from a post because you can then
// refresh the page without getting a "resubmit form" dialog.
void httpSeeOther(const char *otherURL);
// implementation of write used to implement Print interface
virtual size_t write(uint8_t);
virtual size_t write(const char *str);
virtual size_t write(const uint8_t *buffer, size_t size);
size_t write(const char *data, size_t length);
private:
EthernetServer m_server;
EthernetClient m_client;
const char *m_urlPrefix;
unsigned char m_pushback[32];
char m_pushbackDepth;
int m_contentLength;
char m_authCredentials[51];
bool m_readingContent;
Command *m_failureCmd;
Command *m_defaultCmd;
struct CommandMap
{
const char *verb;
Command *cmd;
} m_commands[8];
char m_cmdCount;
void reset();
void getRequest(WebServer::ConnectionType &type, char *request, int *length);
bool dispatchCommand(ConnectionType requestType, char *verb,
bool tail_complete);
void processHeaders();
void outputCheckboxOrRadio(const char *element, const char *name,
const char *val, const char *label,
bool selected);
static void defaultFailCmd(WebServer &server, ConnectionType type,
char *url_tail, bool tail_complete);
void noRobots(ConnectionType type);
void favicon(ConnectionType type);
};
/* define this macro if you want to include the header in a sketch source
file but not define any of the implementation. This is useful if
multiple source files are using the Webduino class. */
#ifndef WEBDUINO_NO_IMPLEMENTATION
/********************************************************************
* IMPLEMENTATION
********************************************************************/
WebServer::WebServer(const char *urlPrefix, int port) :
m_server(port),
m_client(255),
m_urlPrefix(urlPrefix),
m_pushbackDepth(0),
m_cmdCount(0),
m_contentLength(0),
m_failureCmd(&defaultFailCmd),
m_defaultCmd(&defaultFailCmd)
{
}
void WebServer::begin()
{
m_server.begin();
}
void WebServer::setDefaultCommand(Command *cmd)
{
m_defaultCmd = cmd;
}
void WebServer::setFailureCommand(Command *cmd)
{
m_failureCmd = cmd;
}
void WebServer::addCommand(const char *verb, Command *cmd)
{
if (m_cmdCount < SIZE(m_commands))
{
m_commands[m_cmdCount].verb = verb;
m_commands[m_cmdCount++].cmd = cmd;
}
}
size_t WebServer::write(uint8_t ch)
{
return m_client.write(ch);
}
size_t WebServer::write(const char *str)
{
return m_client.write(str);
}
size_t WebServer::write(const uint8_t *buffer, size_t size)
{
return m_client.write(buffer, size);
}
size_t WebServer::write(const char *buffer, size_t length)
{
return m_client.write((const uint8_t *)buffer, length);
}
void WebServer::writeP(const prog_uchar *data, size_t length)
{
// copy data out of program memory into local storage, write out in
// chunks of 32 bytes to avoid extra short TCP/IP packets
uint8_t buffer[32];
size_t bufferEnd = 0;
while (length--)
{
if (bufferEnd == 32)
{
m_client.write(buffer, 32);
bufferEnd = 0;
}
buffer[bufferEnd++] = pgm_read_byte(data++);
}
if (bufferEnd > 0)
m_client.write(buffer, bufferEnd);
}
void WebServer::printP(const prog_uchar *str)
{
// copy data out of program memory into local storage, write out in
// chunks of 32 bytes to avoid extra short TCP/IP packets
uint8_t buffer[32];
size_t bufferEnd = 0;
while (buffer[bufferEnd++] = pgm_read_byte(str++))
{
if (bufferEnd == 32)
{
m_client.write(buffer, 32);
bufferEnd = 0;
}
}
// write out everything left but trailing NUL
if (bufferEnd > 1)
m_client.write(buffer, bufferEnd - 1);
}
void WebServer::printCRLF()
{
m_client.write((const uint8_t *)"\r\n", 2);
}
bool WebServer::dispatchCommand(ConnectionType requestType, char *verb,
bool tail_complete)
{
// if there is no URL, i.e. we have a prefix and it's requested without a
// trailing slash or if the URL is just the slash
if ((verb[0] == 0) || ((verb[0] == '/') && (verb[1] == 0)))
{
m_defaultCmd(*this, requestType, "", tail_complete);
return true;
}
// if the URL is just a slash followed by a question mark
// we're looking at the default command with GET parameters passed
if ((verb[0] == '/') && (verb[1] == '?'))
{
verb+=2; // skip over the "/?" part of the url
m_defaultCmd(*this, requestType, verb, tail_complete);
return true;
}
// We now know that the URL contains at least one character. And,
// if the first character is a slash, there's more after it.
if (verb[0] == '/')
{
char i;
char *qm_loc;
int verb_len;
int qm_offset;
// Skip over the leading "/", because it makes the code more
// efficient and easier to understand.
verb++;
// Look for a "?" separating the filename part of the URL from the
// parameters. If it's not there, compare to the whole URL.
qm_loc = strchr(verb, '?');
verb_len = (qm_loc == NULL) ? strlen(verb) : (qm_loc - verb);
qm_offset = (qm_loc == NULL) ? 0 : 1;
for (i = 0; i < m_cmdCount; ++i)
{
if ((verb_len == strlen(m_commands[i].verb))
&& (strncmp(verb, m_commands[i].verb, verb_len) == 0))
{
// Skip over the "verb" part of the URL (and the question
// mark, if present) when passing it to the "action" routine
m_commands[i].cmd(*this, requestType,
verb + verb_len + qm_offset,
tail_complete);
return true;
}
}
}
return false;
}
// processConnection with a default buffer
void WebServer::processConnection()
{
char request[WEBDUINO_DEFAULT_REQUEST_LENGTH];
int request_len = WEBDUINO_DEFAULT_REQUEST_LENGTH;
processConnection(request, &request_len);
}
void WebServer::processConnection(char *buff, int *bufflen)
{
int urlPrefixLen = strlen(m_urlPrefix);
m_client = m_server.available();
if (m_client) {
m_readingContent = false;
buff[0] = 0;
ConnectionType requestType = INVALID;
#if WEBDUINO_SERIAL_DEBUGGING > 1
Serial.println("*** checking request ***");
#endif
getRequest(requestType, buff, bufflen);
#if WEBDUINO_SERIAL_DEBUGGING > 1
Serial.print("*** requestType = ");
Serial.print((int)requestType);
Serial.print(", request = \"");
Serial.print(buff);
Serial.println("\" ***");
#endif
// don't even look further at invalid requests.
// this is done to prevent Webduino from hanging
// - when there are illegal requests,
// - when someone contacts it through telnet rather than proper HTTP,
// - etc.
if (requestType != INVALID)
{
processHeaders();
#if WEBDUINO_SERIAL_DEBUGGING > 1
Serial.println("*** headers complete ***");
#endif
if (strcmp(buff, "/robots.txt") == 0)
{
noRobots(requestType);
}
else if (strcmp(buff, "/favicon.ico") == 0)
{
favicon(requestType);
}
}
if (requestType == INVALID ||
strncmp(buff, m_urlPrefix, urlPrefixLen) != 0 ||
!dispatchCommand(requestType, buff + urlPrefixLen,
(*bufflen) >= 0))
{
m_failureCmd(*this, requestType, buff, (*bufflen) >= 0);
}
#if WEBDUINO_SERIAL_DEBUGGING > 1
Serial.println("*** stopping connection ***");
#endif
reset();
}
}
bool WebServer::checkCredentials(const char authCredentials[45])
{
char basic[7] = "Basic ";
if((0 == strncmp(m_authCredentials,basic,6)) &&
(0 == strcmp(authCredentials, m_authCredentials + 6))) return true;
return false;
}
void WebServer::httpFail()
{
P(failMsg) =
"HTTP/1.0 400 Bad Request" CRLF
WEBDUINO_SERVER_HEADER
"Content-Type: text/html" CRLF
CRLF
WEBDUINO_FAIL_MESSAGE;
printP(failMsg);
}
void WebServer::defaultFailCmd(WebServer &server,
WebServer::ConnectionType type,
char *url_tail,
bool tail_complete)
{
server.httpFail();
}
void WebServer::noRobots(ConnectionType type)
{
httpSuccess("text/plain");
if (type != HEAD)
{
P(allowNoneMsg) = "User-agent: *" CRLF "Disallow: /" CRLF;
printP(allowNoneMsg);
}
}
void WebServer::favicon(ConnectionType type)
{
httpSuccess("image/x-icon","Cache-Control: max-age=31536000\r\n");
if (type != HEAD)
{
P(faviconIco) = WEBDUINO_FAVICON_DATA;
writeP(faviconIco, sizeof(faviconIco));
}
}
void WebServer::httpUnauthorized()
{
P(failMsg) =
"HTTP/1.0 401 Authorization Required" CRLF
WEBDUINO_SERVER_HEADER
"Content-Type: text/html" CRLF
"WWW-Authenticate: Basic realm=\"" WEBDUINO_AUTH_REALM "\"" CRLF
CRLF
WEBDUINO_AUTH_MESSAGE;
printP(failMsg);
}
void WebServer::httpServerError()
{
P(failMsg) =
"HTTP/1.0 500 Internal Server Error" CRLF
WEBDUINO_SERVER_HEADER
"Content-Type: text/html" CRLF
CRLF
WEBDUINO_SERVER_ERROR_MESSAGE;
printP(failMsg);
}
void WebServer::httpSuccess(const char *contentType,
const char *extraHeaders)
{
P(successMsg1) =
"HTTP/1.0 200 OK" CRLF
WEBDUINO_SERVER_HEADER
"Access-Control-Allow-Origin: *" CRLF
"Content-Type: ";
printP(successMsg1);
print(contentType);
printCRLF();
if (extraHeaders)
print(extraHeaders);
printCRLF();
}
void WebServer::httpSeeOther(const char *otherURL)
{
P(seeOtherMsg) =
"HTTP/1.0 303 See Other" CRLF
WEBDUINO_SERVER_HEADER
"Location: ";
printP(seeOtherMsg);
print(otherURL);
printCRLF();
printCRLF();
}
int WebServer::read()
{
if (m_client == (EthernetClient) 0)
return -1;
if (m_pushbackDepth == 0)
{
unsigned long timeoutTime = millis() + WEBDUINO_READ_TIMEOUT_IN_MS;
while (m_client.connected())
{
// stop reading the socket early if we get to content-length
// characters in the POST. This is because some clients leave
// the socket open because they assume HTTP keep-alive.
if (m_readingContent)
{
if (m_contentLength == 0)
{
#if WEBDUINO_SERIAL_DEBUGGING > 1
Serial.println("\n*** End of content, terminating connection");
#endif
return -1;
}
--m_contentLength;
}
int ch = m_client.read();
// if we get a character, return it, otherwise continue in while
// loop, checking connection status
if (ch != -1)
{
#if WEBDUINO_SERIAL_DEBUGGING
if (ch == '\r')
Serial.print("<CR>");
else if (ch == '\n')
Serial.println("<LF>");
else
Serial.print((char)ch);
#endif
return ch;
}
else
{
unsigned long now = millis();
if (now > timeoutTime)
{
// connection timed out, destroy client, return EOF
#if WEBDUINO_SERIAL_DEBUGGING
Serial.println("*** Connection timed out");
#endif
reset();
return -1;
}
}
}
// connection lost, return EOF
#if WEBDUINO_SERIAL_DEBUGGING
Serial.println("*** Connection lost");
#endif
return -1;
}
else
return m_pushback[--m_pushbackDepth];
}
void WebServer::push(int ch)
{
// don't allow pushing EOF
if (ch == -1)
return;
m_pushback[m_pushbackDepth++] = ch;
// can't raise error here, so just replace last char over and over
if (m_pushbackDepth == SIZE(m_pushback))
m_pushbackDepth = SIZE(m_pushback) - 1;
}
void WebServer::reset()
{
m_pushbackDepth = 0;
m_client.flush();
m_client.stop();
}
bool WebServer::expect(const char *str)
{
const char *curr = str;
while (*curr != 0)
{
int ch = read();
if (ch != *curr++)
{
// push back ch and the characters we accepted
push(ch);
while (--curr != str)
push(curr[-1]);
return false;
}
}
return true;
}
bool WebServer::readInt(int &number)
{
bool negate = false;
bool gotNumber = false;
int ch;
number = 0;
// absorb whitespace
do
{
ch = read();
} while (ch == ' ' || ch == '\t');
// check for leading minus sign
if (ch == '-')
{
negate = true;
ch = read();
}
// read digits to update number, exit when we find non-digit
while (ch >= '0' && ch <= '9')
{
gotNumber = true;
number = number * 10 + ch - '0';
ch = read();
}
push(ch);
if (negate)
number = -number;
return gotNumber;
}
void WebServer::readHeader(char *value, int valueLen)
{
int ch;
memset(value, 0, valueLen);
--valueLen;
// absorb whitespace
do
{
ch = read();
} while (ch == ' ' || ch == '\t');
// read rest of line
do
{
if (valueLen > 1)
{
*value++=ch;
--valueLen;
ch = read();
}
} while (ch != '\r');
push(ch);
}
bool WebServer::readPOSTparam(char *name, int nameLen,
char *value, int valueLen)
{
// assume name is at current place in stream
int ch;
// clear out name and value so they'll be NUL terminated
memset(name, 0, nameLen);
memset(value, 0, valueLen);
// decrement length so we don't write into NUL terminator
--nameLen;
--valueLen;
while ((ch = read()) != -1)
{
if (ch == '+')
{
ch = ' ';
}
else if (ch == '=')
{
/* that's end of name, so switch to storing in value */
nameLen = 0;
continue;
}
else if (ch == '&')
{
/* that's end of pair, go away */
return true;
}
else if (ch == '%')
{
/* handle URL encoded characters by converting back to original form */
int ch1 = read();
int ch2 = read();
if (ch1 == -1 || ch2 == -1)
return false;
char hex[3] = { ch1, ch2, 0 };
ch = strtoul(hex, NULL, 16);
}
// output the new character into the appropriate buffer or drop it if
// there's no room in either one. This code will malfunction in the
// case where the parameter name is too long to fit into the name buffer,
// but in that case, it will just overflow into the value buffer so
// there's no harm.
if (nameLen > 0)
{
*name++ = ch;
--nameLen;
}
else if (valueLen > 0)
{
*value++ = ch;
--valueLen;
}
}
// if we get here, we hit the end-of-file, so POST is over and there
// are no more parameters
return false;
}
/* Retrieve a parameter that was encoded as part of the URL, stored in
* the buffer pointed to by *tail. tail is updated to point just past
* the last character read from the buffer. */
URLPARAM_RESULT WebServer::nextURLparam(char **tail, char *name, int nameLen,
char *value, int valueLen)
{
// assume name is at current place in stream
char ch, hex[3];
URLPARAM_RESULT result = URLPARAM_OK;
char *s = *tail;
bool keep_scanning = true;
bool need_value = true;
// clear out name and value so they'll be NUL terminated
memset(name, 0, nameLen);
memset(value, 0, valueLen);
if (*s == 0)
return URLPARAM_EOS;
// Read the keyword name
while (keep_scanning)
{
ch = *s++;
switch (ch)
{
case 0:
s--; // Back up to point to terminating NUL
// Fall through to "stop the scan" code
case '&':
/* that's end of pair, go away */
keep_scanning = false;
need_value = false;
break;
case '+':
ch = ' ';
break;
case '%':
/* handle URL encoded characters by converting back
* to original form */
if ((hex[0] = *s++) == 0)
{
s--; // Back up to NUL
keep_scanning = false;
need_value = false;
}
else
{
if ((hex[1] = *s++) == 0)
{
s--; // Back up to NUL
keep_scanning = false;
need_value = false;
}
else
{
hex[2] = 0;
ch = strtoul(hex, NULL, 16);
}
}
break;
case '=':
/* that's end of name, so switch to storing in value */
keep_scanning = false;
break;
}
// check against 1 so we don't overwrite the final NUL
if (keep_scanning && (nameLen > 1))
{
*name++ = ch;
--nameLen;
}
else
result = URLPARAM_NAME_OFLO;
}
if (need_value && (*s != 0))
{
keep_scanning = true;
while (keep_scanning)
{
ch = *s++;
switch (ch)
{
case 0:
s--; // Back up to point to terminating NUL
// Fall through to "stop the scan" code
case '&':
/* that's end of pair, go away */
keep_scanning = false;
need_value = false;
break;
case '+':
ch = ' ';
break;
case '%':
/* handle URL encoded characters by converting back to original form */
if ((hex[0] = *s++) == 0)
{
s--; // Back up to NUL
keep_scanning = false;
need_value = false;
}
else
{
if ((hex[1] = *s++) == 0)
{
s--; // Back up to NUL
keep_scanning = false;
need_value = false;
}
else
{
hex[2] = 0;
ch = strtoul(hex, NULL, 16);
}
}
break;
}
// check against 1 so we don't overwrite the final NUL
if (keep_scanning && (valueLen > 1))
{
*value++ = ch;
--valueLen;
}