1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-file-style: "k&r"; c-basic-offset: 2; -*-
3 Webduino, a simple Arduino web server
4 Copyright 2009-2012 Ben Combee, Ran Talbott, Christopher Lee, Martin Lormes
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:
13 The above copyright notice and this permission notice shall be included in
14 all copies or substantial portions of the Software.
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
31 #include <EthernetClient.h>
32 #include <EthernetServer.h>
34 /********************************************************************
36 ********************************************************************/
38 #define WEBDUINO_VERSION 1007
39 #define WEBDUINO_VERSION_STRING "1.7"
41 #if WEBDUINO_SUPRESS_SERVER_HEADER
42 #define WEBDUINO_SERVER_HEADER ""
44 #define WEBDUINO_SERVER_HEADER "Server: Webduino/" WEBDUINO_VERSION_STRING CRLF
47 // standard END-OF-LINE marker in HTTP
50 // If processConnection is called without a buffer, it allocates one
52 #define WEBDUINO_DEFAULT_REQUEST_LENGTH 32
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
60 #ifndef WEBDUINO_URL_PATH_COMMAND_LENGTH
61 #define WEBDUINO_URL_PATH_COMMAND_LENGTH 8
64 #ifndef WEBDUINO_FAIL_MESSAGE
65 #define WEBDUINO_FAIL_MESSAGE "<h1>EPIC FAIL</h1>"
68 #ifndef WEBDUINO_AUTH_REALM
69 #define WEBDUINO_AUTH_REALM "Webduino"
70 #endif // #ifndef WEBDUINO_AUTH_REALM
72 #ifndef WEBDUINO_AUTH_MESSAGE
73 #define WEBDUINO_AUTH_MESSAGE "<h1>401 Unauthorized</h1>"
74 #endif // #ifndef WEBDUINO_AUTH_MESSAGE
76 #ifndef WEBDUINO_SERVER_ERROR_MESSAGE
77 #define WEBDUINO_SERVER_ERROR_MESSAGE "<h1>500 Internal Server Error</h1>"
78 #endif // WEBDUINO_SERVER_ERROR_MESSAGE
80 #ifndef WEBDUINO_OUTPUT_BUFFER_SIZE
81 #define WEBDUINO_OUTPUT_BUFFER_SIZE 32
82 #endif // WEBDUINO_OUTPUT_BUFFER_SIZE
84 // add '#define WEBDUINO_FAVICON_DATA ""' to your application
85 // before including WebServer.h to send a null file as the favicon.ico file
86 // otherwise this defaults to a 16x16 px black diode on blue ground
87 // (or include your own icon if you like)
88 #ifndef WEBDUINO_FAVICON_DATA
89 #define WEBDUINO_FAVICON_DATA { 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, \
90 0x10, 0x02, 0x00, 0x01, 0x00, 0x01, 0x00, \
91 0xb0, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, \
92 0x00, 0x28, 0x00, 0x00, 0x00, 0x10, 0x00, \
93 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, \
94 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, \
95 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
96 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
97 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
98 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, \
99 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, \
100 0x00, 0xff, 0xff, 0x00, 0x00, 0xcf, 0xbf, \
101 0x00, 0x00, 0xc7, 0xbf, 0x00, 0x00, 0xc3, \
102 0xbf, 0x00, 0x00, 0xc1, 0xbf, 0x00, 0x00, \
103 0xc0, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, \
104 0x00, 0xc0, 0xbf, 0x00, 0x00, 0xc1, 0xbf, \
105 0x00, 0x00, 0xc3, 0xbf, 0x00, 0x00, 0xc7, \
106 0xbf, 0x00, 0x00, 0xcf, 0xbf, 0x00, 0x00, \
107 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 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, 0x00, 0x00, 0x00, 0x00, 0x00, \
114 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
115 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
116 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
118 #endif // #ifndef WEBDUINO_FAVICON_DATA
120 // add "#define WEBDUINO_SERIAL_DEBUGGING 1" to your application
121 // before including WebServer.h to have incoming requests logged to
123 #ifndef WEBDUINO_SERIAL_DEBUGGING
124 #define WEBDUINO_SERIAL_DEBUGGING 0
126 #if WEBDUINO_SERIAL_DEBUGGING
127 #include <HardwareSerial.h>
130 // declared in wiring.h
131 extern "C" unsigned long millis(void);
133 // declare a static string
135 #define P(name) static const unsigned char name[] PROGMEM
137 #define P(name) static const unsigned char name[]
140 // returns the number of elements in the array
141 #define SIZE(array) (sizeof(array) / sizeof(*array))
143 #ifdef _VARIANT_ARDUINO_DUE_X_
144 #define pgm_read_byte(ptr) (unsigned char)(* ptr)
146 /********************************************************************
148 ********************************************************************/
150 /* Return codes from nextURLparam. NOTE: URLPARAM_EOS is returned
151 * when you call nextURLparam AFTER the last parameter is read. The
152 * last actual parameter gets an "OK" return code. */
154 enum URLPARAM_RESULT { URLPARAM_OK,
158 URLPARAM_EOS // No params left
161 class WebServer: public Print
164 // passed to a command to indicate what kind of request was received
165 enum ConnectionType { INVALID, GET, HEAD, POST, PUT, DELETE, PATCH };
167 // any commands registered with the web server have to follow
169 // url_tail contains the part of the URL that wasn't matched against
170 // the registered command table.
171 // tail_complete is true if the complete URL fit in url_tail, false if
172 // part of it was lost because the buffer was too small.
173 typedef void Command(WebServer &server, ConnectionType type,
174 char *url_tail, bool tail_complete);
176 // Prototype for the optional function which consumes the URL path itself.
177 // url_path contains pointers to the seperate parts of the URL path where '/'
178 // was used as the delimiter.
179 typedef void UrlPathCommand(WebServer &server, ConnectionType type,
180 char **url_path, char *url_tail,
183 // constructor for webserver object
184 WebServer(const char *urlPrefix = "", int port = 80);
186 // start listening for connections
189 // check for an incoming connection, and if it exists, process it
190 // by reading its request and calling the appropriate command
191 // handler. This version is for compatibility with apps written for
192 // version 1.1, and allocates the URL "tail" buffer internally.
193 void processConnection();
195 // check for an incoming connection, and if it exists, process it
196 // by reading its request and calling the appropriate command
197 // handler. This version saves the "tail" of the URL in buff.
198 void processConnection(char *buff, int *bufflen);
200 // set command that's run when you access the root of the server
201 void setDefaultCommand(Command *cmd);
203 // set command run for undefined pages
204 void setFailureCommand(Command *cmd);
206 // add a new command to be run at the URL specified by verb
207 void addCommand(const char *verb, Command *cmd);
209 // Set command that's run if default command or URL specified commands do
210 // not run, uses extra url_path parameter to allow resolving the URL in the
212 void setUrlPathCommand(UrlPathCommand *cmd);
214 // utility function to output CRLF pair
217 // output a string stored in program memory, usually one defined
219 void printP(const unsigned char *str);
221 // inline overload for printP to handle signed char strings
222 void printP(const char *str) { printP((unsigned char*)str); }
224 // output raw data stored in program memory
225 void writeP(const unsigned char *data, size_t length);
227 // output HTML for a radio button
228 void radioButton(const char *name, const char *val,
229 const char *label, bool selected);
231 // output HTML for a checkbox
232 void checkBox(const char *name, const char *val,
233 const char *label, bool selected);
235 // returns next character or -1 if we're at end-of-stream
238 // put a character that's been read back into the input pool
241 // returns true if the string is next in the stream. Doesn't
242 // consume any character if false, so can be used to try out
243 // different expected values.
244 bool expect(const char *expectedStr);
246 // returns true if a number, with possible whitespace in front, was
247 // read from the server stream. number will be set with the new
248 // value or 0 if nothing was read.
249 bool readInt(int &number);
251 // reads a header value, stripped of possible whitespace in front,
252 // from the server stream
253 void readHeader(char *value, int valueLen);
255 // Read the next keyword parameter from the socket. Assumes that other
256 // code has already skipped over the headers, and the next thing to
257 // be read will be the start of a keyword.
259 // returns true if we're not at end-of-stream
260 bool readPOSTparam(char *name, int nameLen, char *value, int valueLen);
262 // Read the next keyword parameter from the buffer filled by getRequest.
264 // returns 0 if everything weent okay, non-zero if not
265 // (see the typedef for codes)
266 URLPARAM_RESULT nextURLparam(char **tail, char *name, int nameLen,
267 char *value, int valueLen);
269 // compare string against credentials in current request
271 // authCredentials must be Base64 encoded outside of Webduino
272 // (I wanted to be easy on the resources)
274 // returns true if strings match, false otherwise
275 bool checkCredentials(const char authCredentials[45]);
277 // output headers and a message indicating a server error
280 // output headers and a message indicating "401 Unauthorized"
281 void httpUnauthorized();
283 // output headers and a message indicating "500 Internal Server Error"
284 void httpServerError();
286 // output headers indicating "204 No Content" and no further message
287 void httpNoContent();
289 // output standard headers indicating "200 Success". You can change the
290 // type of the data you're outputting or also add extra headers like
291 // "Refresh: 1". Extra headers should each be terminated with CRLF.
292 void httpSuccess(const char *contentType = "text/html; charset=utf-8",
293 const char *extraHeaders = NULL);
295 // used with POST to output a redirect to another URL. This is
296 // preferable to outputting HTML from a post because you can then
297 // refresh the page without getting a "resubmit form" dialog.
298 void httpSeeOther(const char *otherURL);
300 // implementation of write used to implement Print interface
301 virtual size_t write(uint8_t);
303 // tells if there is anything to process
307 EthernetServer m_server;
308 EthernetClient m_client;
309 const char *m_urlPrefix;
311 unsigned char m_pushback[32];
312 unsigned char m_pushbackDepth;
315 char m_authCredentials[51];
316 bool m_readingContent;
318 Command *m_failureCmd;
319 Command *m_defaultCmd;
325 unsigned char m_cmdCount;
326 UrlPathCommand *m_urlPathCmd;
328 uint8_t m_buffer[WEBDUINO_OUTPUT_BUFFER_SIZE];
332 void getRequest(WebServer::ConnectionType &type, char *request, int *length);
333 bool dispatchCommand(ConnectionType requestType, char *verb,
335 void processHeaders();
336 void outputCheckboxOrRadio(const char *element, const char *name,
337 const char *val, const char *label,
340 static void defaultFailCmd(WebServer &server, ConnectionType type,
341 char *url_tail, bool tail_complete);
342 void noRobots(ConnectionType type);
343 void favicon(ConnectionType type);
347 /* define this macro if you want to include the header in a sketch source
348 file but not define any of the implementation. This is useful if
349 multiple source files are using the Webduino class. */
350 #ifndef WEBDUINO_NO_IMPLEMENTATION
352 /********************************************************************
354 ********************************************************************/
356 WebServer::WebServer(const char *urlPrefix, int port) :
358 m_client(MAX_SOCK_NUM),
359 m_urlPrefix(urlPrefix),
362 m_failureCmd(&defaultFailCmd),
363 m_defaultCmd(&defaultFailCmd),
370 void WebServer::begin()
375 void WebServer::setDefaultCommand(Command *cmd)
380 void WebServer::setFailureCommand(Command *cmd)
385 void WebServer::addCommand(const char *verb, Command *cmd)
387 if (m_cmdCount < SIZE(m_commands))
389 m_commands[m_cmdCount].verb = verb;
390 m_commands[m_cmdCount++].cmd = cmd;
394 void WebServer::setUrlPathCommand(UrlPathCommand *cmd)
399 size_t WebServer::write(uint8_t ch)
401 m_buffer[m_bufFill++] = ch;
403 if(m_bufFill == sizeof(m_buffer))
405 m_client.write(m_buffer, sizeof(m_buffer));
412 void WebServer::flushBuf()
416 m_client.write(m_buffer, m_bufFill);
421 void WebServer::writeP(const unsigned char *data, size_t length)
423 // copy data out of program memory into local storage
427 write(pgm_read_byte(data++));
431 void WebServer::printP(const unsigned char *str)
433 // copy data out of program memory into local storage
435 while (uint8_t value = pgm_read_byte(str++))
441 void WebServer::printCRLF()
446 bool WebServer::dispatchCommand(ConnectionType requestType, char *verb,
449 // if there is no URL, i.e. we have a prefix and it's requested without a
450 // trailing slash or if the URL is just the slash
451 if ((verb[0] == 0) || ((verb[0] == '/') && (verb[1] == 0)))
453 m_defaultCmd(*this, requestType, (char*)"", tail_complete);
456 // if the URL is just a slash followed by a question mark
457 // we're looking at the default command with GET parameters passed
458 if ((verb[0] == '/') && (verb[1] == '?'))
460 verb+=2; // skip over the "/?" part of the url
461 m_defaultCmd(*this, requestType, verb, tail_complete);
464 // We now know that the URL contains at least one character. And,
465 // if the first character is a slash, there's more after it.
470 unsigned int verb_len;
472 // Skip over the leading "/", because it makes the code more
473 // efficient and easier to understand.
475 // Look for a "?" separating the filename part of the URL from the
476 // parameters. If it's not there, compare to the whole URL.
477 qm_loc = strchr(verb, '?');
478 verb_len = (qm_loc == NULL) ? strlen(verb) : (qm_loc - verb);
479 qm_offset = (qm_loc == NULL) ? 0 : 1;
480 for (i = 0; i < m_cmdCount; ++i)
482 if ((verb_len == strlen(m_commands[i].verb))
483 && (strncmp(verb, m_commands[i].verb, verb_len) == 0))
485 // Skip over the "verb" part of the URL (and the question
486 // mark, if present) when passing it to the "action" routine
487 m_commands[i].cmd(*this, requestType,
488 verb + verb_len + qm_offset,
493 // Check if UrlPathCommand is assigned.
494 if (m_urlPathCmd != NULL)
496 // Initialize with null bytes, so number of parts can be determined.
497 char *url_path[WEBDUINO_URL_PATH_COMMAND_LENGTH] = {0};
500 // URL path should be terminated with null byte.
501 *(verb + verb_len) = 0;
503 // First URL path part is at the start of verb.
504 url_path[part++] = verb;
505 // Replace all slashes ('/') with a null byte so every part of the URL
506 // path is a seperate string. Add every char following a '/' as a new
507 // part of the URL, even if that char is a '/' (which will be replaced
508 // with a null byte).
509 for (char * p = verb; p < verb + verb_len; p++)
514 url_path[part++] = p + 1;
515 // Don't try to assign out of array bounds.
516 if (part == WEBDUINO_URL_PATH_COMMAND_LENGTH) break;
519 m_urlPathCmd(*this, requestType, url_path,
520 verb + verb_len + qm_offset, tail_complete);
527 // processConnection with a default buffer
528 void WebServer::processConnection()
530 char request[WEBDUINO_DEFAULT_REQUEST_LENGTH];
531 int request_len = WEBDUINO_DEFAULT_REQUEST_LENGTH;
532 processConnection(request, &request_len);
535 void WebServer::processConnection(char *buff, int *bufflen)
537 int urlPrefixLen = strlen(m_urlPrefix);
539 m_client = m_server.available();
542 m_readingContent = false;
544 ConnectionType requestType = INVALID;
545 #if WEBDUINO_SERIAL_DEBUGGING > 1
546 Serial.println("*** checking request ***");
548 getRequest(requestType, buff, bufflen);
549 #if WEBDUINO_SERIAL_DEBUGGING > 1
550 Serial.print("*** requestType = ");
551 Serial.print((int)requestType);
552 Serial.print(", request = \"");
554 Serial.println("\" ***");
557 // don't even look further at invalid requests.
558 // this is done to prevent Webduino from hanging
559 // - when there are illegal requests,
560 // - when someone contacts it through telnet rather than proper HTTP,
562 if (requestType != INVALID)
565 #if WEBDUINO_SERIAL_DEBUGGING > 1
566 Serial.println("*** headers complete ***");
569 if (strcmp(buff, "/robots.txt") == 0)
571 noRobots(requestType);
573 else if (strcmp(buff, "/favicon.ico") == 0)
575 favicon(requestType);
578 // Only try to dispatch command if request type and prefix are correct.
580 if (requestType == INVALID ||
581 strncmp(buff, m_urlPrefix, urlPrefixLen) != 0)
583 m_failureCmd(*this, requestType, buff, (*bufflen) >= 0);
585 else if (!dispatchCommand(requestType, buff + urlPrefixLen,
588 m_failureCmd(*this, requestType, buff, (*bufflen) >= 0);
593 #if WEBDUINO_SERIAL_DEBUGGING > 1
594 Serial.println("*** stopping connection ***");
600 bool WebServer::checkCredentials(const char authCredentials[45])
602 char basic[7] = "Basic ";
603 if((0 == strncmp(m_authCredentials,basic,6)) &&
604 (0 == strcmp(authCredentials, m_authCredentials + 6))) return true;
608 void WebServer::httpFail()
611 "HTTP/1.0 400 Bad Request" CRLF
612 WEBDUINO_SERVER_HEADER
613 "Content-Type: text/html" CRLF
615 WEBDUINO_FAIL_MESSAGE;
620 void WebServer::defaultFailCmd(WebServer &server,
621 WebServer::ConnectionType type,
628 void WebServer::noRobots(ConnectionType type)
630 httpSuccess("text/plain");
633 P(allowNoneMsg) = "User-agent: *" CRLF "Disallow: /" CRLF;
634 printP(allowNoneMsg);
638 void WebServer::favicon(ConnectionType type)
640 httpSuccess("image/x-icon","Cache-Control: max-age=31536000\r\n");
643 P(faviconIco) = WEBDUINO_FAVICON_DATA;
644 writeP(faviconIco, sizeof(faviconIco));
648 void WebServer::httpUnauthorized()
651 "HTTP/1.0 401 Authorization Required" CRLF
652 WEBDUINO_SERVER_HEADER
653 "Content-Type: text/html" CRLF
654 "WWW-Authenticate: Basic realm=\"" WEBDUINO_AUTH_REALM "\"" CRLF
656 WEBDUINO_AUTH_MESSAGE;
661 void WebServer::httpServerError()
664 "HTTP/1.0 500 Internal Server Error" CRLF
665 WEBDUINO_SERVER_HEADER
666 "Content-Type: text/html" CRLF
668 WEBDUINO_SERVER_ERROR_MESSAGE;
673 void WebServer::httpNoContent()
676 "HTTP/1.0 204 NO CONTENT" CRLF
677 WEBDUINO_SERVER_HEADER
681 printP(noContentMsg);
684 void WebServer::httpSuccess(const char *contentType,
685 const char *extraHeaders)
688 "HTTP/1.0 200 OK" CRLF
689 WEBDUINO_SERVER_HEADER
690 "Access-Control-Allow-Origin: *" CRLF
701 void WebServer::httpSeeOther(const char *otherURL)
704 "HTTP/1.0 303 See Other" CRLF
705 WEBDUINO_SERVER_HEADER
714 int WebServer::read()
719 if (m_pushbackDepth == 0)
721 unsigned long timeoutTime = millis() + WEBDUINO_READ_TIMEOUT_IN_MS;
723 while (m_client.connected())
725 // stop reading the socket early if we get to content-length
726 // characters in the POST. This is because some clients leave
727 // the socket open because they assume HTTP keep-alive.
728 if (m_readingContent)
730 if (m_contentLength == 0)
732 #if WEBDUINO_SERIAL_DEBUGGING > 1
733 Serial.println("\n*** End of content, terminating connection");
739 int ch = m_client.read();
741 // if we get a character, return it, otherwise continue in while
742 // loop, checking connection status
745 // count character against content-length
746 if (m_readingContent)
751 #if WEBDUINO_SERIAL_DEBUGGING
753 Serial.print("<CR>");
755 Serial.println("<LF>");
757 Serial.print((char)ch);
763 unsigned long now = millis();
764 if (now > timeoutTime)
766 // connection timed out, destroy client, return EOF
767 #if WEBDUINO_SERIAL_DEBUGGING
768 Serial.println("*** Connection timed out");
776 // connection lost, return EOF
777 #if WEBDUINO_SERIAL_DEBUGGING
778 Serial.println("*** Connection lost");
783 return m_pushback[--m_pushbackDepth];
786 void WebServer::push(int ch)
788 // don't allow pushing EOF
792 m_pushback[m_pushbackDepth++] = ch;
793 // can't raise error here, so just replace last char over and over
794 if (m_pushbackDepth == SIZE(m_pushback))
795 m_pushbackDepth = SIZE(m_pushback) - 1;
798 void WebServer::reset()
805 bool WebServer::expect(const char *str)
807 const char *curr = str;
813 // push back ch and the characters we accepted
815 while (--curr != str)
823 bool WebServer::readInt(int &number)
826 bool gotNumber = false;
834 } while (ch == ' ' || ch == '\t');
836 // check for leading minus sign
843 // read digits to update number, exit when we find non-digit
844 while (ch >= '0' && ch <= '9')
847 number = number * 10 + ch - '0';
857 void WebServer::readHeader(char *value, int valueLen)
860 memset(value, 0, valueLen);
867 } while (ch == ' ' || ch == '\t');
878 } while (ch != '\r');
882 bool WebServer::readPOSTparam(char *name, int nameLen,
883 char *value, int valueLen)
885 // assume name is at current place in stream
887 // to not to miss the last parameter
888 bool foundSomething = false;
890 // clear out name and value so they'll be NUL terminated
891 memset(name, 0, nameLen);
892 memset(value, 0, valueLen);
894 // decrement length so we don't write into NUL terminator
898 while ((ch = read()) != -1)
900 foundSomething = true;
907 /* that's end of name, so switch to storing in value */
913 /* that's end of pair, go away */
918 /* handle URL encoded characters by converting back to original form */
921 if (ch1 == -1 || ch2 == -1)
923 char hex[3] = { ch1, ch2, 0 };
924 ch = strtoul(hex, NULL, 16);
927 // output the new character into the appropriate buffer or drop it if
928 // there's no room in either one. This code will malfunction in the
929 // case where the parameter name is too long to fit into the name buffer,
930 // but in that case, it will just overflow into the value buffer so
937 else if (valueLen > 0)
946 // if we get here, we have one last parameter to serve
951 // if we get here, we hit the end-of-file, so POST is over and there
952 // are no more parameters
957 /* Retrieve a parameter that was encoded as part of the URL, stored in
958 * the buffer pointed to by *tail. tail is updated to point just past
959 * the last character read from the buffer. */
960 URLPARAM_RESULT WebServer::nextURLparam(char **tail, char *name, int nameLen,
961 char *value, int valueLen)
963 // assume name is at current place in stream
965 URLPARAM_RESULT result = URLPARAM_OK;
967 bool keep_scanning = true;
968 bool need_value = true;
970 // clear out name and value so they'll be NUL terminated
971 memset(name, 0, nameLen);
972 memset(value, 0, valueLen);
976 // Read the keyword name
977 while (keep_scanning)
983 s--; // Back up to point to terminating NUL
984 // Fall through to "stop the scan" code
986 /* that's end of pair, go away */
987 keep_scanning = false;
994 /* handle URL encoded characters by converting back
995 * to original form */
996 if ((hex[0] = *s++) == 0)
998 s--; // Back up to NUL
999 keep_scanning = false;
1004 if ((hex[1] = *s++) == 0)
1006 s--; // Back up to NUL
1007 keep_scanning = false;
1013 ch = strtoul(hex, NULL, 16);
1018 /* that's end of name, so switch to storing in value */
1019 keep_scanning = false;
1024 // check against 1 so we don't overwrite the final NUL
1025 if (keep_scanning && (nameLen > 1))
1030 else if(keep_scanning)
1031 result = URLPARAM_NAME_OFLO;
1034 if (need_value && (*s != 0))
1036 keep_scanning = true;
1037 while (keep_scanning)
1043 s--; // Back up to point to terminating NUL
1044 // Fall through to "stop the scan" code
1046 /* that's end of pair, go away */
1047 keep_scanning = false;
1054 /* handle URL encoded characters by converting back to original form */
1055 if ((hex[0] = *s++) == 0)
1057 s--; // Back up to NUL
1058 keep_scanning = false;
1063 if ((hex[1] = *s++) == 0)
1065 s--; // Back up to NUL
1066 keep_scanning = false;
1072 ch = strtoul(hex, NULL, 16);
1080 // check against 1 so we don't overwrite the final NUL
1081 if (keep_scanning && (valueLen > 1))
1086 else if(keep_scanning)
1087 result = (result == URLPARAM_OK) ?
1088 URLPARAM_VALUE_OFLO :
1098 // Read and parse the first line of the request header.
1099 // The "command" (GET/HEAD/POST) is translated into a numeric value in type.
1100 // The URL is stored in request, up to the length passed in length
1101 // NOTE 1: length must include one byte for the terminating NUL.
1102 // NOTE 2: request is NOT checked for NULL, nor length for a value < 1.
1103 // Reading stops when the code encounters a space, CR, or LF. If the HTTP
1104 // version was supplied by the client, it will still be waiting in the input
1105 // stream when we exit.
1107 // On return, length contains the amount of space left in request. If it's
1108 // less than 0, the URL was longer than the buffer, and part of it had to
1111 void WebServer::getRequest(WebServer::ConnectionType &type,
1112 char *request, int *length)
1114 --*length; // save room for NUL
1118 // store the HTTP method line of the request
1121 else if (expect("HEAD "))
1123 else if (expect("POST "))
1125 else if (expect("PUT "))
1127 else if (expect("DELETE "))
1129 else if (expect("PATCH "))
1132 // if it doesn't start with any of those, we have an unknown method
1133 // so just get out of here
1138 while ((ch = read()) != -1)
1140 // stop storing at first space or end of line
1141 if (ch == ' ' || ch == '\n' || ch == '\r')
1156 void WebServer::processHeaders()
1158 // look for three things: the Content-Length header, the Authorization
1159 // header, and the double-CRLF that ends the headers.
1161 // empty the m_authCredentials before every run of this function.
1162 // otherwise users who don't send an Authorization header would be treated
1163 // like the last user who tried to authenticate (possibly successful)
1164 m_authCredentials[0]=0;
1168 if (expect("Content-Length:"))
1170 readInt(m_contentLength);
1171 #if WEBDUINO_SERIAL_DEBUGGING > 1
1172 Serial.print("\n*** got Content-Length of ");
1173 Serial.print(m_contentLength);
1174 Serial.print(" ***");
1179 if (expect("Authorization:"))
1181 readHeader(m_authCredentials,51);
1182 #if WEBDUINO_SERIAL_DEBUGGING > 1
1183 Serial.print("\n*** got Authorization: of ");
1184 Serial.print(m_authCredentials);
1185 Serial.print(" ***");
1190 if (expect(CRLF CRLF))
1192 m_readingContent = true;
1196 // no expect checks hit, so just absorb a character and try again
1204 void WebServer::outputCheckboxOrRadio(const char *element, const char *name,
1205 const char *val, const char *label,
1208 P(cbPart1a) = "<label><input type='";
1209 P(cbPart1b) = "' name='";
1210 P(cbPart2) = "' value='";
1212 P(cbChecked) = "checked ";
1214 P(cbPart5) = "</label>";
1230 void WebServer::checkBox(const char *name, const char *val,
1231 const char *label, bool selected)
1233 outputCheckboxOrRadio("checkbox", name, val, label, selected);
1236 void WebServer::radioButton(const char *name, const char *val,
1237 const char *label, bool selected)
1239 outputCheckboxOrRadio("radio", name, val, label, selected);
1242 uint8_t WebServer::available(){
1243 return m_server.available();
1246 #endif // WEBDUINO_NO_IMPLEMENTATION
1248 #endif // WEBDUINO_H_