]> git.0d.be Git - PanikSwitch.git/blob - WebServer.h
8647e091960d48de344d4adda12905240fca491e
[PanikSwitch.git] / WebServer.h
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil;  c-file-style: "k&r"; c-basic-offset: 2; -*-
2
3    Webduino, a simple Arduino web server
4    Copyright 2009-2012 Ben Combee, Ran Talbott, Christopher Lee, Martin Lormes
5
6    Permission is hereby granted, free of charge, to any person obtaining a copy
7    of this software and associated documentation files (the "Software"), to deal
8    in the Software without restriction, including without limitation the rights
9    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10    copies of the Software, and to permit persons to whom the Software is
11    furnished to do so, subject to the following conditions:
12
13    The above copyright notice and this permission notice shall be included in
14    all copies or substantial portions of the Software.
15
16    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22    THE SOFTWARE.
23 */
24
25 #ifndef WEBDUINO_H_
26 #define WEBDUINO_H_
27
28 #include <string.h>
29 #include <stdlib.h>
30
31 #include <EthernetClient.h>
32 #include <EthernetServer.h>
33
34 /********************************************************************
35  * CONFIGURATION
36  ********************************************************************/
37
38 #define WEBDUINO_VERSION 1007
39 #define WEBDUINO_VERSION_STRING "1.7"
40
41 #if WEBDUINO_SUPRESS_SERVER_HEADER
42 #define WEBDUINO_SERVER_HEADER ""
43 #else
44 #define WEBDUINO_SERVER_HEADER "Server: Webduino/" WEBDUINO_VERSION_STRING CRLF
45 #endif
46
47 // standard END-OF-LINE marker in HTTP
48 #define CRLF "\r\n"
49
50 // If processConnection is called without a buffer, it allocates one
51 // of 32 bytes
52 #define WEBDUINO_DEFAULT_REQUEST_LENGTH 32
53
54 // How long to wait before considering a connection as dead when
55 // reading the HTTP request.  Used to avoid DOS attacks.
56 #ifndef WEBDUINO_READ_TIMEOUT_IN_MS
57 #define WEBDUINO_READ_TIMEOUT_IN_MS 1000
58 #endif
59
60 #ifndef WEBDUINO_URL_PATH_COMMAND_LENGTH
61 #define WEBDUINO_URL_PATH_COMMAND_LENGTH 8
62 #endif
63
64 #ifndef WEBDUINO_FAIL_MESSAGE
65 #define WEBDUINO_FAIL_MESSAGE "<h1>EPIC FAIL</h1>"
66 #endif
67
68 #ifndef WEBDUINO_AUTH_REALM
69 #define WEBDUINO_AUTH_REALM "Webduino"
70 #endif // #ifndef WEBDUINO_AUTH_REALM
71
72 #ifndef WEBDUINO_AUTH_MESSAGE
73 #define WEBDUINO_AUTH_MESSAGE "<h1>401 Unauthorized</h1>"
74 #endif // #ifndef WEBDUINO_AUTH_MESSAGE
75
76 #ifndef WEBDUINO_SERVER_ERROR_MESSAGE
77 #define WEBDUINO_SERVER_ERROR_MESSAGE "<h1>500 Internal Server Error</h1>"
78 #endif // WEBDUINO_SERVER_ERROR_MESSAGE
79
80 // add '#define WEBDUINO_FAVICON_DATA ""' to your application
81 // before including WebServer.h to send a null file as the favicon.ico file
82 // otherwise this defaults to a 16x16 px black diode on blue ground
83 // (or include your own icon if you like)
84 #ifndef WEBDUINO_FAVICON_DATA
85 #define WEBDUINO_FAVICON_DATA { 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, \
86                                 0x10, 0x02, 0x00, 0x01, 0x00, 0x01, 0x00, \
87                                 0xb0, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, \
88                                 0x00, 0x28, 0x00, 0x00, 0x00, 0x10, 0x00, \
89                                 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, \
90                                 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, \
91                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
92                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
93                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
94                                 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, \
95                                 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, \
96                                 0x00, 0xff, 0xff, 0x00, 0x00, 0xcf, 0xbf, \
97                                 0x00, 0x00, 0xc7, 0xbf, 0x00, 0x00, 0xc3, \
98                                 0xbf, 0x00, 0x00, 0xc1, 0xbf, 0x00, 0x00, \
99                                 0xc0, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, \
100                                 0x00, 0xc0, 0xbf, 0x00, 0x00, 0xc1, 0xbf, \
101                                 0x00, 0x00, 0xc3, 0xbf, 0x00, 0x00, 0xc7, \
102                                 0xbf, 0x00, 0x00, 0xcf, 0xbf, 0x00, 0x00, \
103                                 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, \
104                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
105                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
106                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
107                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
108                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
109                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
110                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
111                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
112                                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
113                                 0x00, 0x00 }
114 #endif // #ifndef WEBDUINO_FAVICON_DATA
115
116 // add "#define WEBDUINO_SERIAL_DEBUGGING 1" to your application
117 // before including WebServer.h to have incoming requests logged to
118 // the serial port.
119 #ifndef WEBDUINO_SERIAL_DEBUGGING
120 #define WEBDUINO_SERIAL_DEBUGGING 0
121 #endif
122 #if WEBDUINO_SERIAL_DEBUGGING
123 #include <HardwareSerial.h>
124 #endif
125
126 // declared in wiring.h
127 extern "C" unsigned long millis(void);
128
129 // declare a static string
130 #define P(name)   static const unsigned char name[] PROGMEM
131
132 // returns the number of elements in the array
133 #define SIZE(array) (sizeof(array) / sizeof(*array))
134
135 /********************************************************************
136  * DECLARATIONS
137  ********************************************************************/
138
139 /* Return codes from nextURLparam.  NOTE: URLPARAM_EOS is returned
140  * when you call nextURLparam AFTER the last parameter is read.  The
141  * last actual parameter gets an "OK" return code. */
142
143 typedef enum URLPARAM_RESULT { URLPARAM_OK,
144                                URLPARAM_NAME_OFLO,
145                                URLPARAM_VALUE_OFLO,
146                                URLPARAM_BOTH_OFLO,
147                                URLPARAM_EOS         // No params left
148 };
149
150 class WebServer: public Print
151 {
152 public:
153   // passed to a command to indicate what kind of request was received
154   enum ConnectionType { INVALID, GET, HEAD, POST, PUT, DELETE, PATCH };
155
156   // any commands registered with the web server have to follow
157   // this prototype.
158   // url_tail contains the part of the URL that wasn't matched against
159   //          the registered command table.
160   // tail_complete is true if the complete URL fit in url_tail,  false if
161   //          part of it was lost because the buffer was too small.
162   typedef void Command(WebServer &server, ConnectionType type,
163                        char *url_tail, bool tail_complete);
164
165   // Prototype for the optional function which consumes the URL path itself.
166   // url_path contains pointers to the seperate parts of the URL path where '/'
167   //          was used as the delimiter.
168   typedef void UrlPathCommand(WebServer &server, ConnectionType type,
169                               char **url_path, char *url_tail,
170                               bool tail_complete);
171
172   // constructor for webserver object
173   WebServer(const char *urlPrefix = "", int port = 80);
174
175   // start listening for connections
176   void begin();
177
178   // check for an incoming connection, and if it exists, process it
179   // by reading its request and calling the appropriate command
180   // handler.  This version is for compatibility with apps written for
181   // version 1.1,  and allocates the URL "tail" buffer internally.
182   void processConnection();
183
184   // check for an incoming connection, and if it exists, process it
185   // by reading its request and calling the appropriate command
186   // handler.  This version saves the "tail" of the URL in buff.
187   void processConnection(char *buff, int *bufflen);
188
189   // set command that's run when you access the root of the server
190   void setDefaultCommand(Command *cmd);
191
192   // set command run for undefined pages
193   void setFailureCommand(Command *cmd);
194
195   // add a new command to be run at the URL specified by verb
196   void addCommand(const char *verb, Command *cmd);
197
198   // Set command that's run if default command or URL specified commands do
199   // not run, uses extra url_path parameter to allow resolving the URL in the
200   // function.
201   void setUrlPathCommand(UrlPathCommand *cmd);
202
203   // utility function to output CRLF pair
204   void printCRLF();
205
206   // output a string stored in program memory, usually one defined
207   // with the P macro
208   void printP(const unsigned char *str);
209
210   // inline overload for printP to handle signed char strings
211   void printP(const char *str) { printP((unsigned char*)str); }
212
213   // output raw data stored in program memory
214   void writeP(const unsigned char *data, size_t length);
215
216   // output HTML for a radio button
217   void radioButton(const char *name, const char *val,
218                    const char *label, bool selected);
219
220   // output HTML for a checkbox
221   void checkBox(const char *name, const char *val,
222                 const char *label, bool selected);
223
224   // returns next character or -1 if we're at end-of-stream
225   int read();
226
227   // put a character that's been read back into the input pool
228   void push(int ch);
229
230   // returns true if the string is next in the stream.  Doesn't
231   // consume any character if false, so can be used to try out
232   // different expected values.
233   bool expect(const char *expectedStr);
234
235   // returns true if a number, with possible whitespace in front, was
236   // read from the server stream.  number will be set with the new
237   // value or 0 if nothing was read.
238   bool readInt(int &number);
239
240   // reads a header value, stripped of possible whitespace in front,
241   // from the server stream
242   void readHeader(char *value, int valueLen);
243
244   // Read the next keyword parameter from the socket.  Assumes that other
245   // code has already skipped over the headers,  and the next thing to
246   // be read will be the start of a keyword.
247   //
248   // returns true if we're not at end-of-stream
249   bool readPOSTparam(char *name, int nameLen, char *value, int valueLen);
250
251   // Read the next keyword parameter from the buffer filled by getRequest.
252   //
253   // returns 0 if everything weent okay,  non-zero if not
254   // (see the typedef for codes)
255   URLPARAM_RESULT nextURLparam(char **tail, char *name, int nameLen,
256                                char *value, int valueLen);
257
258   // compare string against credentials in current request
259   //
260   // authCredentials must be Base64 encoded outside of Webduino
261   // (I wanted to be easy on the resources)
262   //
263   // returns true if strings match, false otherwise
264   bool checkCredentials(const char authCredentials[45]);
265
266   // output headers and a message indicating a server error
267   void httpFail();
268   
269   // output headers and a message indicating "401 Unauthorized"
270   void httpUnauthorized();
271
272   // output headers and a message indicating "500 Internal Server Error"
273   void httpServerError();
274
275   // output headers indicating "204 No Content" and no further message
276   void httpNoContent();
277
278   // output standard headers indicating "200 Success".  You can change the
279   // type of the data you're outputting or also add extra headers like
280   // "Refresh: 1".  Extra headers should each be terminated with CRLF.
281   void httpSuccess(const char *contentType = "text/html; charset=utf-8",
282                    const char *extraHeaders = NULL);
283
284   // used with POST to output a redirect to another URL.  This is
285   // preferable to outputting HTML from a post because you can then
286   // refresh the page without getting a "resubmit form" dialog.
287   void httpSeeOther(const char *otherURL);
288
289   // implementation of write used to implement Print interface
290   virtual size_t write(uint8_t);
291   virtual size_t write(const char *str);
292   virtual size_t write(const uint8_t *buffer, size_t size);
293   size_t write(const char *data, size_t length);
294
295   // tells if there is anything to process
296   uint8_t available();
297
298 private:
299   EthernetServer m_server;
300   EthernetClient m_client;
301   const char *m_urlPrefix;
302
303   unsigned char m_pushback[32];
304   char m_pushbackDepth;
305
306   int m_contentLength;
307   char m_authCredentials[51];
308   bool m_readingContent;
309
310   Command *m_failureCmd;
311   Command *m_defaultCmd;
312   struct CommandMap
313   {
314     const char *verb;
315     Command *cmd;
316   } m_commands[8];
317   char m_cmdCount;
318   UrlPathCommand *m_urlPathCmd;
319
320   void reset();
321   void getRequest(WebServer::ConnectionType &type, char *request, int *length);
322   bool dispatchCommand(ConnectionType requestType, char *verb,
323                        bool tail_complete);
324   void processHeaders();
325   void outputCheckboxOrRadio(const char *element, const char *name,
326                              const char *val, const char *label,
327                              bool selected);
328
329   static void defaultFailCmd(WebServer &server, ConnectionType type,
330                              char *url_tail, bool tail_complete);
331   void noRobots(ConnectionType type);
332   void favicon(ConnectionType type);
333 };
334
335 /* define this macro if you want to include the header in a sketch source
336    file but not define any of the implementation. This is useful if
337    multiple source files are using the Webduino class. */
338 #ifndef WEBDUINO_NO_IMPLEMENTATION
339
340 /********************************************************************
341  * IMPLEMENTATION
342  ********************************************************************/
343
344 WebServer::WebServer(const char *urlPrefix, int port) :
345   m_server(port),
346   m_client(255),
347   m_urlPrefix(urlPrefix),
348   m_pushbackDepth(0),
349   m_cmdCount(0),
350   m_contentLength(0),
351   m_failureCmd(&defaultFailCmd),
352   m_defaultCmd(&defaultFailCmd),
353   m_urlPathCmd(NULL)
354 {
355 }
356
357 void WebServer::begin()
358 {
359   m_server.begin();
360 }
361
362 void WebServer::setDefaultCommand(Command *cmd)
363 {
364   m_defaultCmd = cmd;
365 }
366
367 void WebServer::setFailureCommand(Command *cmd)
368 {
369   m_failureCmd = cmd;
370 }
371
372 void WebServer::addCommand(const char *verb, Command *cmd)
373 {
374   if (m_cmdCount < SIZE(m_commands))
375   {
376     m_commands[m_cmdCount].verb = verb;
377     m_commands[m_cmdCount++].cmd = cmd;
378   }
379 }
380
381 void WebServer::setUrlPathCommand(UrlPathCommand *cmd)
382 {
383   m_urlPathCmd = cmd;
384 }
385
386 size_t WebServer::write(uint8_t ch)
387 {
388   return m_client.write(ch);
389 }
390
391 size_t WebServer::write(const char *str)
392 {
393   return m_client.write(str);
394 }
395
396 size_t WebServer::write(const uint8_t *buffer, size_t size)
397 {
398   return m_client.write(buffer, size);
399 }
400
401 size_t WebServer::write(const char *buffer, size_t length)
402 {
403   return m_client.write((const uint8_t *)buffer, length);
404 }
405
406 void WebServer::writeP(const unsigned char *data, size_t length)
407 {
408   // copy data out of program memory into local storage, write out in
409   // chunks of 32 bytes to avoid extra short TCP/IP packets
410   uint8_t buffer[32];
411   size_t bufferEnd = 0;
412
413   while (length--)
414   {
415     if (bufferEnd == 32)
416     {
417       m_client.write(buffer, 32);
418       bufferEnd = 0;
419     }
420
421     buffer[bufferEnd++] = pgm_read_byte(data++);
422   }
423
424   if (bufferEnd > 0)
425     m_client.write(buffer, bufferEnd);
426 }
427
428 void WebServer::printP(const unsigned char *str)
429 {
430   // copy data out of program memory into local storage, write out in
431   // chunks of 32 bytes to avoid extra short TCP/IP packets
432   uint8_t buffer[32];
433   size_t bufferEnd = 0;
434   
435   while (buffer[bufferEnd++] = pgm_read_byte(str++))
436   {
437     if (bufferEnd == 32)
438     {
439       m_client.write(buffer, 32);
440       bufferEnd = 0;
441     }
442   }
443
444   // write out everything left but trailing NUL
445   if (bufferEnd > 1)
446     m_client.write(buffer, bufferEnd - 1);
447 }
448
449 void WebServer::printCRLF()
450 {
451   m_client.write((const uint8_t *)"\r\n", 2);
452 }
453
454 bool WebServer::dispatchCommand(ConnectionType requestType, char *verb,
455         bool tail_complete)
456 {
457   // if there is no URL, i.e. we have a prefix and it's requested without a 
458   // trailing slash or if the URL is just the slash
459   if ((verb[0] == 0) || ((verb[0] == '/') && (verb[1] == 0)))
460   {
461     m_defaultCmd(*this, requestType, "", tail_complete);
462     return true;
463   }
464   // if the URL is just a slash followed by a question mark
465   // we're looking at the default command with GET parameters passed
466   if ((verb[0] == '/') && (verb[1] == '?'))
467   {
468     verb+=2; // skip over the "/?" part of the url
469     m_defaultCmd(*this, requestType, verb, tail_complete);
470     return true;
471   }
472   // We now know that the URL contains at least one character.  And,
473   // if the first character is a slash,  there's more after it.
474   if (verb[0] == '/')
475   {
476     char i;
477     char *qm_loc;
478     int verb_len;
479     int qm_offset;
480     // Skip over the leading "/",  because it makes the code more
481     // efficient and easier to understand.
482     verb++;
483     // Look for a "?" separating the filename part of the URL from the
484     // parameters.  If it's not there, compare to the whole URL.
485     qm_loc = strchr(verb, '?');
486     verb_len = (qm_loc == NULL) ? strlen(verb) : (qm_loc - verb);
487     qm_offset = (qm_loc == NULL) ? 0 : 1;
488     for (i = 0; i < m_cmdCount; ++i)
489     {
490       if ((verb_len == strlen(m_commands[i].verb))
491           && (strncmp(verb, m_commands[i].verb, verb_len) == 0))
492       {
493         // Skip over the "verb" part of the URL (and the question
494         // mark, if present) when passing it to the "action" routine
495         m_commands[i].cmd(*this, requestType,
496         verb + verb_len + qm_offset,
497         tail_complete);
498         return true;
499       }
500     }
501     // Check if UrlPathCommand is assigned.
502     if (m_urlPathCmd != NULL)
503     {
504       // Initialize with null bytes, so number of parts can be determined.
505       char *url_path[WEBDUINO_URL_PATH_COMMAND_LENGTH] = {0};
506       int part = 0;
507
508       // URL path should be terminated with null byte.
509       *(verb + verb_len) = 0;
510
511       // First URL path part is at the start of verb.
512       url_path[part++] = verb;
513       // Replace all slashes ('/') with a null byte so every part of the URL
514       // path is a seperate string. Add every char following a '/' as a new
515       // part of the URL, even if that char is a '/' (which will be replaced
516       // with a null byte).
517       for (char * p = verb; p < verb + verb_len; p++)
518       {
519         if (*p == '/')
520         {
521           *p = 0;
522           url_path[part++] = p + 1;
523           // Don't try to assign out of array bounds.
524           if (part == WEBDUINO_URL_PATH_COMMAND_LENGTH) break;
525         }
526       }
527       m_urlPathCmd(*this, requestType, url_path,
528                    verb + verb_len + qm_offset, tail_complete);
529       return true;
530     }
531   }
532   return false;
533 }
534
535 // processConnection with a default buffer
536 void WebServer::processConnection()
537 {
538   char request[WEBDUINO_DEFAULT_REQUEST_LENGTH];
539   int  request_len = WEBDUINO_DEFAULT_REQUEST_LENGTH;
540   processConnection(request, &request_len);
541 }
542
543 void WebServer::processConnection(char *buff, int *bufflen)
544 {
545   int urlPrefixLen = strlen(m_urlPrefix);
546
547   m_client = m_server.available();
548
549   if (m_client) {
550     m_readingContent = false;
551     buff[0] = 0;
552     ConnectionType requestType = INVALID;
553 #if WEBDUINO_SERIAL_DEBUGGING > 1
554     Serial.println("*** checking request ***");
555 #endif
556     getRequest(requestType, buff, bufflen);
557 #if WEBDUINO_SERIAL_DEBUGGING > 1
558     Serial.print("*** requestType = ");
559     Serial.print((int)requestType);
560     Serial.print(", request = \"");
561     Serial.print(buff);
562     Serial.println("\" ***");
563 #endif
564
565     // don't even look further at invalid requests.
566     // this is done to prevent Webduino from hanging
567     // - when there are illegal requests,
568     // - when someone contacts it through telnet rather than proper HTTP,
569     // - etc.
570     if (requestType != INVALID)
571     {
572       processHeaders();
573 #if WEBDUINO_SERIAL_DEBUGGING > 1
574       Serial.println("*** headers complete ***");
575 #endif
576
577       if (strcmp(buff, "/robots.txt") == 0)
578       {
579         noRobots(requestType);
580       }
581       else if (strcmp(buff, "/favicon.ico") == 0)
582       {
583         favicon(requestType);
584       }
585     }
586     // Only try to dispatch command if request type and prefix are correct.
587     // Fix by quarencia.
588     if (requestType == INVALID ||
589         strncmp(buff, m_urlPrefix, urlPrefixLen) != 0)
590     {
591       m_failureCmd(*this, requestType, buff, (*bufflen) >= 0);
592     }
593     else if (!dispatchCommand(requestType, buff + urlPrefixLen,
594              (*bufflen) >= 0))
595     {
596       m_failureCmd(*this, requestType, buff, (*bufflen) >= 0);
597     }
598
599 #if WEBDUINO_SERIAL_DEBUGGING > 1
600     Serial.println("*** stopping connection ***");
601 #endif
602     reset();
603   }
604 }
605
606 bool WebServer::checkCredentials(const char authCredentials[45])
607 {
608   char basic[7] = "Basic ";
609   if((0 == strncmp(m_authCredentials,basic,6)) && 
610      (0 == strcmp(authCredentials, m_authCredentials + 6))) return true;
611   return false;
612 }
613
614 void WebServer::httpFail()
615 {
616   P(failMsg) =
617     "HTTP/1.0 400 Bad Request" CRLF
618     WEBDUINO_SERVER_HEADER
619     "Content-Type: text/html" CRLF
620     CRLF
621     WEBDUINO_FAIL_MESSAGE;
622
623   printP(failMsg);
624 }
625
626 void WebServer::defaultFailCmd(WebServer &server,
627                                WebServer::ConnectionType type,
628                                char *url_tail,
629                                bool tail_complete)
630 {
631   server.httpFail();
632 }
633
634 void WebServer::noRobots(ConnectionType type)
635 {
636   httpSuccess("text/plain");
637   if (type != HEAD)
638   {
639     P(allowNoneMsg) = "User-agent: *" CRLF "Disallow: /" CRLF;
640     printP(allowNoneMsg);
641   }
642 }
643
644 void WebServer::favicon(ConnectionType type)
645 {
646   httpSuccess("image/x-icon","Cache-Control: max-age=31536000\r\n");
647   if (type != HEAD)
648   {
649     P(faviconIco) = WEBDUINO_FAVICON_DATA;
650     writeP(faviconIco, sizeof(faviconIco));
651   }
652 }
653
654 void WebServer::httpUnauthorized()
655 {
656   P(failMsg) =
657     "HTTP/1.0 401 Authorization Required" CRLF
658     WEBDUINO_SERVER_HEADER
659     "Content-Type: text/html" CRLF
660     "WWW-Authenticate: Basic realm=\"" WEBDUINO_AUTH_REALM "\"" CRLF
661     CRLF
662     WEBDUINO_AUTH_MESSAGE;
663
664   printP(failMsg);
665 }
666
667 void WebServer::httpServerError()
668 {
669   P(failMsg) =
670     "HTTP/1.0 500 Internal Server Error" CRLF
671     WEBDUINO_SERVER_HEADER
672     "Content-Type: text/html" CRLF
673     CRLF
674     WEBDUINO_SERVER_ERROR_MESSAGE;
675
676   printP(failMsg);
677 }
678
679 void WebServer::httpNoContent()
680 {
681   P(noContentMsg) =
682     "HTTP/1.0 204 NO CONTENT" CRLF
683     WEBDUINO_SERVER_HEADER
684     CRLF
685     CRLF;
686
687   printP(noContentMsg);
688 }
689
690 void WebServer::httpSuccess(const char *contentType,
691                             const char *extraHeaders)
692 {
693   P(successMsg1) =
694     "HTTP/1.0 200 OK" CRLF
695     WEBDUINO_SERVER_HEADER
696     "Access-Control-Allow-Origin: *" CRLF
697     "Content-Type: ";
698
699   printP(successMsg1);
700   print(contentType);
701   printCRLF();
702   if (extraHeaders)
703     print(extraHeaders);
704   printCRLF();
705 }
706
707 void WebServer::httpSeeOther(const char *otherURL)
708 {
709   P(seeOtherMsg) =
710     "HTTP/1.0 303 See Other" CRLF
711     WEBDUINO_SERVER_HEADER
712     "Location: ";
713
714   printP(seeOtherMsg);
715   print(otherURL);
716   printCRLF();
717   printCRLF();
718 }
719
720 int WebServer::read()
721 {
722   if (m_client == NULL)
723     return -1;
724
725   if (m_pushbackDepth == 0)
726   {
727     unsigned long timeoutTime = millis() + WEBDUINO_READ_TIMEOUT_IN_MS;
728
729     while (m_client.connected())
730     {
731       // stop reading the socket early if we get to content-length
732       // characters in the POST.  This is because some clients leave
733       // the socket open because they assume HTTP keep-alive.
734       if (m_readingContent)
735       {
736         if (m_contentLength == 0)
737         {
738 #if WEBDUINO_SERIAL_DEBUGGING > 1
739           Serial.println("\n*** End of content, terminating connection");
740 #endif
741           return -1;
742         }
743       }
744
745       int ch = m_client.read();
746
747       // if we get a character, return it, otherwise continue in while
748       // loop, checking connection status
749       if (ch != -1)
750       {
751         // count character against content-length
752         if (m_readingContent)
753         {
754           --m_contentLength;
755         }
756
757 #if WEBDUINO_SERIAL_DEBUGGING
758         if (ch == '\r')
759           Serial.print("<CR>");
760         else if (ch == '\n')
761           Serial.println("<LF>");
762         else
763           Serial.print((char)ch);
764 #endif
765         return ch;
766       }
767       else
768       {
769         unsigned long now = millis();
770         if (now > timeoutTime)
771         {
772           // connection timed out, destroy client, return EOF
773 #if WEBDUINO_SERIAL_DEBUGGING
774           Serial.println("*** Connection timed out");
775 #endif
776           reset();
777           return -1;
778         }
779       }
780     }
781
782     // connection lost, return EOF
783 #if WEBDUINO_SERIAL_DEBUGGING
784     Serial.println("*** Connection lost");
785 #endif
786     return -1;
787   }
788   else
789     return m_pushback[--m_pushbackDepth];
790 }
791
792 void WebServer::push(int ch)
793 {
794   // don't allow pushing EOF
795   if (ch == -1)
796     return;
797
798   m_pushback[m_pushbackDepth++] = ch;
799   // can't raise error here, so just replace last char over and over
800   if (m_pushbackDepth == SIZE(m_pushback))
801     m_pushbackDepth = SIZE(m_pushback) - 1;
802 }
803
804 void WebServer::reset()
805 {
806   m_pushbackDepth = 0;
807   m_client.flush();
808   m_client.stop();
809 }
810
811 bool WebServer::expect(const char *str)
812 {
813   const char *curr = str;
814   while (*curr != 0)
815   {
816     int ch = read();
817     if (ch != *curr++)
818     {
819       // push back ch and the characters we accepted
820       push(ch);
821       while (--curr != str)
822         push(curr[-1]);
823       return false;
824     }
825   }
826   return true;
827 }
828
829 bool WebServer::readInt(int &number)
830 {
831   bool negate = false;
832   bool gotNumber = false;
833   int ch;
834   number = 0;
835
836   // absorb whitespace
837   do
838   {
839     ch = read();
840   } while (ch == ' ' || ch == '\t');
841
842   // check for leading minus sign
843   if (ch == '-')
844   {
845     negate = true;
846     ch = read();
847   }
848
849   // read digits to update number, exit when we find non-digit
850   while (ch >= '0' && ch <= '9')
851   {
852     gotNumber = true;
853     number = number * 10 + ch - '0';
854     ch = read();
855   }
856
857   push(ch);
858   if (negate)
859     number = -number;
860   return gotNumber;
861 }
862
863 void WebServer::readHeader(char *value, int valueLen)
864 {
865   int ch;
866   memset(value, 0, valueLen);
867   --valueLen;
868
869   // absorb whitespace
870   do
871   {
872     ch = read();
873   } while (ch == ' ' || ch == '\t');
874
875   // read rest of line
876   do
877   {
878     if (valueLen > 1)
879     {
880       *value++=ch;
881       --valueLen;
882     }
883     ch = read();
884   } while (ch != '\r');
885   push(ch);
886 }
887
888 bool WebServer::readPOSTparam(char *name, int nameLen,
889                               char *value, int valueLen)
890 {
891   // assume name is at current place in stream
892   int ch;
893   // to not to miss the last parameter
894   bool foundSomething = false;
895
896   // clear out name and value so they'll be NUL terminated
897   memset(name, 0, nameLen);
898   memset(value, 0, valueLen);
899
900   // decrement length so we don't write into NUL terminator
901   --nameLen;
902   --valueLen;
903
904   while ((ch = read()) != -1)
905   {
906     foundSomething = true;
907     if (ch == '+')
908     {
909       ch = ' ';
910     }
911     else if (ch == '=')
912     {
913       /* that's end of name, so switch to storing in value */
914       nameLen = 0;
915       continue;
916     }
917     else if (ch == '&')
918     {
919       /* that's end of pair, go away */
920       return true;
921     }
922     else if (ch == '%')
923     {
924       /* handle URL encoded characters by converting back to original form */
925       int ch1 = read();
926       int ch2 = read();
927       if (ch1 == -1 || ch2 == -1)
928         return false;
929       char hex[3] = { ch1, ch2, 0 };
930       ch = strtoul(hex, NULL, 16);
931     }
932
933     // output the new character into the appropriate buffer or drop it if
934     // there's no room in either one.  This code will malfunction in the
935     // case where the parameter name is too long to fit into the name buffer,
936     // but in that case, it will just overflow into the value buffer so
937     // there's no harm.
938     if (nameLen > 0)
939     {
940       *name++ = ch;
941       --nameLen;
942     }
943     else if (valueLen > 0)
944     {
945       *value++ = ch;
946       --valueLen;
947     }
948   }
949
950   if (foundSomething)
951   {
952     // if we get here, we have one last parameter to serve
953     return true;
954   }
955   else
956   {
957     // if we get here, we hit the end-of-file, so POST is over and there
958     // are no more parameters
959     return false;
960   }
961 }
962
963 /* Retrieve a parameter that was encoded as part of the URL, stored in
964  * the buffer pointed to by *tail.  tail is updated to point just past
965  * the last character read from the buffer. */
966 URLPARAM_RESULT WebServer::nextURLparam(char **tail, char *name, int nameLen,
967                                         char *value, int valueLen)
968 {
969   // assume name is at current place in stream
970   char ch, hex[3];
971   URLPARAM_RESULT result = URLPARAM_OK;
972   char *s = *tail;
973   bool keep_scanning = true;
974   bool need_value = true;
975
976   // clear out name and value so they'll be NUL terminated
977   memset(name, 0, nameLen);
978   memset(value, 0, valueLen);
979
980   if (*s == 0)
981     return URLPARAM_EOS;
982   // Read the keyword name
983   while (keep_scanning)
984   {
985     ch = *s++;
986     switch (ch)
987     {
988     case 0:
989       s--;  // Back up to point to terminating NUL
990       // Fall through to "stop the scan" code
991     case '&':
992       /* that's end of pair, go away */
993       keep_scanning = false;
994       need_value = false;
995       break;
996     case '+':
997       ch = ' ';
998       break;
999     case '%':
1000       /* handle URL encoded characters by converting back
1001        * to original form */
1002       if ((hex[0] = *s++) == 0)
1003       {
1004         s--;        // Back up to NUL
1005         keep_scanning = false;
1006         need_value = false;
1007       }
1008       else
1009       {
1010         if ((hex[1] = *s++) == 0)
1011         {
1012           s--;  // Back up to NUL
1013           keep_scanning = false;
1014           need_value = false;
1015         }
1016         else
1017         {
1018           hex[2] = 0;
1019           ch = strtoul(hex, NULL, 16);
1020         }
1021       }
1022       break;
1023     case '=':
1024       /* that's end of name, so switch to storing in value */
1025       keep_scanning = false;
1026       break;
1027     }
1028
1029
1030     // check against 1 so we don't overwrite the final NUL
1031     if (keep_scanning && (nameLen > 1))
1032     {
1033       *name++ = ch;
1034       --nameLen;
1035     }
1036     else
1037       result = URLPARAM_NAME_OFLO;
1038   }
1039
1040   if (need_value && (*s != 0))
1041   {
1042     keep_scanning = true;
1043     while (keep_scanning)
1044     {
1045       ch = *s++;
1046       switch (ch)
1047       {
1048       case 0:
1049         s--;  // Back up to point to terminating NUL
1050               // Fall through to "stop the scan" code
1051       case '&':
1052         /* that's end of pair, go away */
1053         keep_scanning = false;
1054         need_value = false;
1055         break;
1056       case '+':
1057         ch = ' ';
1058         break;
1059       case '%':
1060         /* handle URL encoded characters by converting back to original form */
1061         if ((hex[0] = *s++) == 0)
1062         {
1063           s--;  // Back up to NUL
1064           keep_scanning = false;
1065           need_value = false;
1066         }
1067         else
1068         {
1069           if ((hex[1] = *s++) == 0)
1070           {
1071             s--;  // Back up to NUL
1072             keep_scanning = false;
1073             need_value = false;
1074           }
1075           else
1076           {
1077             hex[2] = 0;
1078             ch = strtoul(hex, NULL, 16);
1079           }
1080
1081         }
1082         break;
1083       }
1084
1085
1086       // check against 1 so we don't overwrite the final NUL
1087       if (keep_scanning && (valueLen > 1))
1088       {
1089         *value++ = ch;
1090         --valueLen;
1091       }
1092       else
1093         result = (result == URLPARAM_OK) ?
1094           URLPARAM_VALUE_OFLO :
1095           URLPARAM_BOTH_OFLO;
1096     }
1097   }
1098   *tail = s;
1099   return result;
1100 }
1101
1102
1103
1104 // Read and parse the first line of the request header.
1105 // The "command" (GET/HEAD/POST) is translated into a numeric value in type.
1106 // The URL is stored in request,  up to the length passed in length
1107 // NOTE 1: length must include one byte for the terminating NUL.
1108 // NOTE 2: request is NOT checked for NULL,  nor length for a value < 1.
1109 // Reading stops when the code encounters a space, CR, or LF.  If the HTTP
1110 // version was supplied by the client,  it will still be waiting in the input
1111 // stream when we exit.
1112 //
1113 // On return, length contains the amount of space left in request.  If it's
1114 // less than 0,  the URL was longer than the buffer,  and part of it had to
1115 // be discarded.
1116
1117 void WebServer::getRequest(WebServer::ConnectionType &type,
1118                            char *request, int *length)
1119 {
1120   --*length; // save room for NUL
1121
1122   type = INVALID;
1123
1124   // store the HTTP method line of the request
1125   if (expect("GET "))
1126     type = GET;
1127   else if (expect("HEAD "))
1128     type = HEAD;
1129   else if (expect("POST "))
1130     type = POST;
1131   else if (expect("PUT "))
1132     type = PUT;
1133   else if (expect("DELETE "))
1134     type = DELETE;
1135   else if (expect("PATCH "))
1136     type = PATCH;
1137
1138   // if it doesn't start with any of those, we have an unknown method
1139   // so just get out of here
1140   else
1141     return;
1142
1143   int ch;
1144   while ((ch = read()) != -1)
1145   {
1146     // stop storing at first space or end of line
1147     if (ch == ' ' || ch == '\n' || ch == '\r')
1148     {
1149       break;
1150     }
1151     if (*length > 0)
1152     {
1153       *request = ch;
1154       ++request;
1155     }
1156     --*length;
1157   }
1158   // NUL terminate
1159   *request = 0;
1160 }
1161
1162 void WebServer::processHeaders()
1163 {
1164   // look for three things: the Content-Length header, the Authorization 
1165   // header, and the double-CRLF that ends the headers.
1166
1167   // empty the m_authCredentials before every run of this function.
1168   // otherwise users who don't send an Authorization header would be treated
1169   // like the last user who tried to authenticate (possibly successful)
1170   m_authCredentials[0]=0;
1171
1172   while (1)
1173   {
1174     if (expect("Content-Length:"))
1175     {
1176       readInt(m_contentLength);
1177 #if WEBDUINO_SERIAL_DEBUGGING > 1
1178       Serial.print("\n*** got Content-Length of ");
1179       Serial.print(m_contentLength);
1180       Serial.print(" ***");
1181 #endif
1182       continue;
1183     }
1184
1185     if (expect("Authorization:"))
1186     {
1187       readHeader(m_authCredentials,51);
1188 #if WEBDUINO_SERIAL_DEBUGGING > 1
1189       Serial.print("\n*** got Authorization: of ");
1190       Serial.print(m_authCredentials);
1191       Serial.print(" ***");
1192 #endif
1193       continue;
1194     }
1195
1196     if (expect(CRLF CRLF))
1197     {
1198       m_readingContent = true;
1199       return;
1200     }
1201
1202     // no expect checks hit, so just absorb a character and try again
1203     if (read() == -1)
1204     {
1205       return;
1206     }
1207   }
1208 }
1209
1210 void WebServer::outputCheckboxOrRadio(const char *element, const char *name,
1211                                       const char *val, const char *label,
1212                                       bool selected)
1213 {
1214   P(cbPart1a) = "<label><input type='";
1215   P(cbPart1b) = "' name='";
1216   P(cbPart2) = "' value='";
1217   P(cbPart3) = "' ";
1218   P(cbChecked) = "checked ";
1219   P(cbPart4) = "/> ";
1220   P(cbPart5) = "</label>";
1221
1222   printP(cbPart1a);
1223   print(element);
1224   printP(cbPart1b);
1225   print(name);
1226   printP(cbPart2);
1227   print(val);
1228   printP(cbPart3);
1229   if (selected)
1230     printP(cbChecked);
1231   printP(cbPart4);
1232   print(label);
1233   printP(cbPart5);
1234 }
1235
1236 void WebServer::checkBox(const char *name, const char *val,
1237                          const char *label, bool selected)
1238 {
1239   outputCheckboxOrRadio("checkbox", name, val, label, selected);
1240 }
1241
1242 void WebServer::radioButton(const char *name, const char *val,
1243                             const char *label, bool selected)
1244 {
1245   outputCheckboxOrRadio("radio", name, val, label, selected);
1246 }
1247
1248 uint8_t WebServer::available(){
1249   return m_server.available();
1250 }
1251
1252 #endif // WEBDUINO_NO_IMPLEMENTATION
1253
1254 #endif // WEBDUINO_H_