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 // 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, \
114 #endif // #ifndef WEBDUINO_FAVICON_DATA
116 // add "#define WEBDUINO_SERIAL_DEBUGGING 1" to your application
117 // before including WebServer.h to have incoming requests logged to
119 #ifndef WEBDUINO_SERIAL_DEBUGGING
120 #define WEBDUINO_SERIAL_DEBUGGING 0
122 #if WEBDUINO_SERIAL_DEBUGGING
123 #include <HardwareSerial.h>
126 // declared in wiring.h
127 extern "C" unsigned long millis(void);
129 // declare a static string
130 #define P(name) static const unsigned char name[] PROGMEM
132 // returns the number of elements in the array
133 #define SIZE(array) (sizeof(array) / sizeof(*array))
135 /********************************************************************
137 ********************************************************************/
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. */
143 typedef enum URLPARAM_RESULT { URLPARAM_OK,
147 URLPARAM_EOS // No params left
150 class WebServer: public Print
153 // passed to a command to indicate what kind of request was received
154 enum ConnectionType { INVALID, GET, HEAD, POST, PUT, DELETE, PATCH };
156 // any commands registered with the web server have to follow
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);
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,
172 // constructor for webserver object
173 WebServer(const char *urlPrefix = "", int port = 80);
175 // start listening for connections
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();
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);
189 // set command that's run when you access the root of the server
190 void setDefaultCommand(Command *cmd);
192 // set command run for undefined pages
193 void setFailureCommand(Command *cmd);
195 // add a new command to be run at the URL specified by verb
196 void addCommand(const char *verb, Command *cmd);
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
201 void setUrlPathCommand(UrlPathCommand *cmd);
203 // utility function to output CRLF pair
206 // output a string stored in program memory, usually one defined
208 void printP(const unsigned char *str);
210 // inline overload for printP to handle signed char strings
211 void printP(const char *str) { printP((unsigned char*)str); }
213 // output raw data stored in program memory
214 void writeP(const unsigned char *data, size_t length);
216 // output HTML for a radio button
217 void radioButton(const char *name, const char *val,
218 const char *label, bool selected);
220 // output HTML for a checkbox
221 void checkBox(const char *name, const char *val,
222 const char *label, bool selected);
224 // returns next character or -1 if we're at end-of-stream
227 // put a character that's been read back into the input pool
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);
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);
240 // reads a header value, stripped of possible whitespace in front,
241 // from the server stream
242 void readHeader(char *value, int valueLen);
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.
248 // returns true if we're not at end-of-stream
249 bool readPOSTparam(char *name, int nameLen, char *value, int valueLen);
251 // Read the next keyword parameter from the buffer filled by getRequest.
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);
258 // compare string against credentials in current request
260 // authCredentials must be Base64 encoded outside of Webduino
261 // (I wanted to be easy on the resources)
263 // returns true if strings match, false otherwise
264 bool checkCredentials(const char authCredentials[45]);
266 // output headers and a message indicating a server error
269 // output headers and a message indicating "401 Unauthorized"
270 void httpUnauthorized();
272 // output headers and a message indicating "500 Internal Server Error"
273 void httpServerError();
275 // output headers indicating "204 No Content" and no further message
276 void httpNoContent();
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);
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);
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);
295 // tells if there is anything to process
299 EthernetServer m_server;
300 EthernetClient m_client;
301 const char *m_urlPrefix;
303 unsigned char m_pushback[32];
304 char m_pushbackDepth;
307 char m_authCredentials[51];
308 bool m_readingContent;
310 Command *m_failureCmd;
311 Command *m_defaultCmd;
318 UrlPathCommand *m_urlPathCmd;
321 void getRequest(WebServer::ConnectionType &type, char *request, int *length);
322 bool dispatchCommand(ConnectionType requestType, char *verb,
324 void processHeaders();
325 void outputCheckboxOrRadio(const char *element, const char *name,
326 const char *val, const char *label,
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);
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
340 /********************************************************************
342 ********************************************************************/
344 WebServer::WebServer(const char *urlPrefix, int port) :
347 m_urlPrefix(urlPrefix),
351 m_failureCmd(&defaultFailCmd),
352 m_defaultCmd(&defaultFailCmd),
357 void WebServer::begin()
362 void WebServer::setDefaultCommand(Command *cmd)
367 void WebServer::setFailureCommand(Command *cmd)
372 void WebServer::addCommand(const char *verb, Command *cmd)
374 if (m_cmdCount < SIZE(m_commands))
376 m_commands[m_cmdCount].verb = verb;
377 m_commands[m_cmdCount++].cmd = cmd;
381 void WebServer::setUrlPathCommand(UrlPathCommand *cmd)
386 size_t WebServer::write(uint8_t ch)
388 return m_client.write(ch);
391 size_t WebServer::write(const char *str)
393 return m_client.write(str);
396 size_t WebServer::write(const uint8_t *buffer, size_t size)
398 return m_client.write(buffer, size);
401 size_t WebServer::write(const char *buffer, size_t length)
403 return m_client.write((const uint8_t *)buffer, length);
406 void WebServer::writeP(const unsigned char *data, size_t length)
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
411 size_t bufferEnd = 0;
417 m_client.write(buffer, 32);
421 buffer[bufferEnd++] = pgm_read_byte(data++);
425 m_client.write(buffer, bufferEnd);
428 void WebServer::printP(const unsigned char *str)
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
433 size_t bufferEnd = 0;
435 while (buffer[bufferEnd++] = pgm_read_byte(str++))
439 m_client.write(buffer, 32);
444 // write out everything left but trailing NUL
446 m_client.write(buffer, bufferEnd - 1);
449 void WebServer::printCRLF()
451 m_client.write((const uint8_t *)"\r\n", 2);
454 bool WebServer::dispatchCommand(ConnectionType requestType, char *verb,
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)))
461 m_defaultCmd(*this, requestType, "", tail_complete);
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] == '?'))
468 verb+=2; // skip over the "/?" part of the url
469 m_defaultCmd(*this, requestType, verb, tail_complete);
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.
480 // Skip over the leading "/", because it makes the code more
481 // efficient and easier to understand.
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)
490 if ((verb_len == strlen(m_commands[i].verb))
491 && (strncmp(verb, m_commands[i].verb, verb_len) == 0))
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,
501 // Check if UrlPathCommand is assigned.
502 if (m_urlPathCmd != NULL)
504 // Initialize with null bytes, so number of parts can be determined.
505 char *url_path[WEBDUINO_URL_PATH_COMMAND_LENGTH] = {0};
508 // URL path should be terminated with null byte.
509 *(verb + verb_len) = 0;
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++)
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;
527 m_urlPathCmd(*this, requestType, url_path,
528 verb + verb_len + qm_offset, tail_complete);
535 // processConnection with a default buffer
536 void WebServer::processConnection()
538 char request[WEBDUINO_DEFAULT_REQUEST_LENGTH];
539 int request_len = WEBDUINO_DEFAULT_REQUEST_LENGTH;
540 processConnection(request, &request_len);
543 void WebServer::processConnection(char *buff, int *bufflen)
545 int urlPrefixLen = strlen(m_urlPrefix);
547 m_client = m_server.available();
550 m_readingContent = false;
552 ConnectionType requestType = INVALID;
553 #if WEBDUINO_SERIAL_DEBUGGING > 1
554 Serial.println("*** checking request ***");
556 getRequest(requestType, buff, bufflen);
557 #if WEBDUINO_SERIAL_DEBUGGING > 1
558 Serial.print("*** requestType = ");
559 Serial.print((int)requestType);
560 Serial.print(", request = \"");
562 Serial.println("\" ***");
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,
570 if (requestType != INVALID)
573 #if WEBDUINO_SERIAL_DEBUGGING > 1
574 Serial.println("*** headers complete ***");
577 if (strcmp(buff, "/robots.txt") == 0)
579 noRobots(requestType);
581 else if (strcmp(buff, "/favicon.ico") == 0)
583 favicon(requestType);
586 // Only try to dispatch command if request type and prefix are correct.
588 if (requestType == INVALID ||
589 strncmp(buff, m_urlPrefix, urlPrefixLen) != 0)
591 m_failureCmd(*this, requestType, buff, (*bufflen) >= 0);
593 else if (!dispatchCommand(requestType, buff + urlPrefixLen,
596 m_failureCmd(*this, requestType, buff, (*bufflen) >= 0);
599 #if WEBDUINO_SERIAL_DEBUGGING > 1
600 Serial.println("*** stopping connection ***");
606 bool WebServer::checkCredentials(const char authCredentials[45])
608 char basic[7] = "Basic ";
609 if((0 == strncmp(m_authCredentials,basic,6)) &&
610 (0 == strcmp(authCredentials, m_authCredentials + 6))) return true;
614 void WebServer::httpFail()
617 "HTTP/1.0 400 Bad Request" CRLF
618 WEBDUINO_SERVER_HEADER
619 "Content-Type: text/html" CRLF
621 WEBDUINO_FAIL_MESSAGE;
626 void WebServer::defaultFailCmd(WebServer &server,
627 WebServer::ConnectionType type,
634 void WebServer::noRobots(ConnectionType type)
636 httpSuccess("text/plain");
639 P(allowNoneMsg) = "User-agent: *" CRLF "Disallow: /" CRLF;
640 printP(allowNoneMsg);
644 void WebServer::favicon(ConnectionType type)
646 httpSuccess("image/x-icon","Cache-Control: max-age=31536000\r\n");
649 P(faviconIco) = WEBDUINO_FAVICON_DATA;
650 writeP(faviconIco, sizeof(faviconIco));
654 void WebServer::httpUnauthorized()
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
662 WEBDUINO_AUTH_MESSAGE;
667 void WebServer::httpServerError()
670 "HTTP/1.0 500 Internal Server Error" CRLF
671 WEBDUINO_SERVER_HEADER
672 "Content-Type: text/html" CRLF
674 WEBDUINO_SERVER_ERROR_MESSAGE;
679 void WebServer::httpNoContent()
682 "HTTP/1.0 204 NO CONTENT" CRLF
683 WEBDUINO_SERVER_HEADER
687 printP(noContentMsg);
690 void WebServer::httpSuccess(const char *contentType,
691 const char *extraHeaders)
694 "HTTP/1.0 200 OK" CRLF
695 WEBDUINO_SERVER_HEADER
696 "Access-Control-Allow-Origin: *" CRLF
707 void WebServer::httpSeeOther(const char *otherURL)
710 "HTTP/1.0 303 See Other" CRLF
711 WEBDUINO_SERVER_HEADER
720 int WebServer::read()
722 if (m_client == NULL)
725 if (m_pushbackDepth == 0)
727 unsigned long timeoutTime = millis() + WEBDUINO_READ_TIMEOUT_IN_MS;
729 while (m_client.connected())
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)
736 if (m_contentLength == 0)
738 #if WEBDUINO_SERIAL_DEBUGGING > 1
739 Serial.println("\n*** End of content, terminating connection");
745 int ch = m_client.read();
747 // if we get a character, return it, otherwise continue in while
748 // loop, checking connection status
751 // count character against content-length
752 if (m_readingContent)
757 #if WEBDUINO_SERIAL_DEBUGGING
759 Serial.print("<CR>");
761 Serial.println("<LF>");
763 Serial.print((char)ch);
769 unsigned long now = millis();
770 if (now > timeoutTime)
772 // connection timed out, destroy client, return EOF
773 #if WEBDUINO_SERIAL_DEBUGGING
774 Serial.println("*** Connection timed out");
782 // connection lost, return EOF
783 #if WEBDUINO_SERIAL_DEBUGGING
784 Serial.println("*** Connection lost");
789 return m_pushback[--m_pushbackDepth];
792 void WebServer::push(int ch)
794 // don't allow pushing EOF
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;
804 void WebServer::reset()
811 bool WebServer::expect(const char *str)
813 const char *curr = str;
819 // push back ch and the characters we accepted
821 while (--curr != str)
829 bool WebServer::readInt(int &number)
832 bool gotNumber = false;
840 } while (ch == ' ' || ch == '\t');
842 // check for leading minus sign
849 // read digits to update number, exit when we find non-digit
850 while (ch >= '0' && ch <= '9')
853 number = number * 10 + ch - '0';
863 void WebServer::readHeader(char *value, int valueLen)
866 memset(value, 0, valueLen);
873 } while (ch == ' ' || ch == '\t');
884 } while (ch != '\r');
888 bool WebServer::readPOSTparam(char *name, int nameLen,
889 char *value, int valueLen)
891 // assume name is at current place in stream
893 // to not to miss the last parameter
894 bool foundSomething = false;
896 // clear out name and value so they'll be NUL terminated
897 memset(name, 0, nameLen);
898 memset(value, 0, valueLen);
900 // decrement length so we don't write into NUL terminator
904 while ((ch = read()) != -1)
906 foundSomething = true;
913 /* that's end of name, so switch to storing in value */
919 /* that's end of pair, go away */
924 /* handle URL encoded characters by converting back to original form */
927 if (ch1 == -1 || ch2 == -1)
929 char hex[3] = { ch1, ch2, 0 };
930 ch = strtoul(hex, NULL, 16);
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
943 else if (valueLen > 0)
952 // if we get here, we have one last parameter to serve
957 // if we get here, we hit the end-of-file, so POST is over and there
958 // are no more parameters
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)
969 // assume name is at current place in stream
971 URLPARAM_RESULT result = URLPARAM_OK;
973 bool keep_scanning = true;
974 bool need_value = true;
976 // clear out name and value so they'll be NUL terminated
977 memset(name, 0, nameLen);
978 memset(value, 0, valueLen);
982 // Read the keyword name
983 while (keep_scanning)
989 s--; // Back up to point to terminating NUL
990 // Fall through to "stop the scan" code
992 /* that's end of pair, go away */
993 keep_scanning = false;
1000 /* handle URL encoded characters by converting back
1001 * to original form */
1002 if ((hex[0] = *s++) == 0)
1004 s--; // Back up to NUL
1005 keep_scanning = false;
1010 if ((hex[1] = *s++) == 0)
1012 s--; // Back up to NUL
1013 keep_scanning = false;
1019 ch = strtoul(hex, NULL, 16);
1024 /* that's end of name, so switch to storing in value */
1025 keep_scanning = false;
1030 // check against 1 so we don't overwrite the final NUL
1031 if (keep_scanning && (nameLen > 1))
1037 result = URLPARAM_NAME_OFLO;
1040 if (need_value && (*s != 0))
1042 keep_scanning = true;
1043 while (keep_scanning)
1049 s--; // Back up to point to terminating NUL
1050 // Fall through to "stop the scan" code
1052 /* that's end of pair, go away */
1053 keep_scanning = false;
1060 /* handle URL encoded characters by converting back to original form */
1061 if ((hex[0] = *s++) == 0)
1063 s--; // Back up to NUL
1064 keep_scanning = false;
1069 if ((hex[1] = *s++) == 0)
1071 s--; // Back up to NUL
1072 keep_scanning = false;
1078 ch = strtoul(hex, NULL, 16);
1086 // check against 1 so we don't overwrite the final NUL
1087 if (keep_scanning && (valueLen > 1))
1093 result = (result == URLPARAM_OK) ?
1094 URLPARAM_VALUE_OFLO :
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.
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
1117 void WebServer::getRequest(WebServer::ConnectionType &type,
1118 char *request, int *length)
1120 --*length; // save room for NUL
1124 // store the HTTP method line of the request
1127 else if (expect("HEAD "))
1129 else if (expect("POST "))
1131 else if (expect("PUT "))
1133 else if (expect("DELETE "))
1135 else if (expect("PATCH "))
1138 // if it doesn't start with any of those, we have an unknown method
1139 // so just get out of here
1144 while ((ch = read()) != -1)
1146 // stop storing at first space or end of line
1147 if (ch == ' ' || ch == '\n' || ch == '\r')
1162 void WebServer::processHeaders()
1164 // look for three things: the Content-Length header, the Authorization
1165 // header, and the double-CRLF that ends the headers.
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;
1174 if (expect("Content-Length:"))
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(" ***");
1185 if (expect("Authorization:"))
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(" ***");
1196 if (expect(CRLF CRLF))
1198 m_readingContent = true;
1202 // no expect checks hit, so just absorb a character and try again
1210 void WebServer::outputCheckboxOrRadio(const char *element, const char *name,
1211 const char *val, const char *label,
1214 P(cbPart1a) = "<label><input type='";
1215 P(cbPart1b) = "' name='";
1216 P(cbPart2) = "' value='";
1218 P(cbChecked) = "checked ";
1220 P(cbPart5) = "</label>";
1236 void WebServer::checkBox(const char *name, const char *val,
1237 const char *label, bool selected)
1239 outputCheckboxOrRadio("checkbox", name, val, label, selected);
1242 void WebServer::radioButton(const char *name, const char *val,
1243 const char *label, bool selected)
1245 outputCheckboxOrRadio("radio", name, val, label, selected);
1248 uint8_t WebServer::available(){
1249 return m_server.available();
1252 #endif // WEBDUINO_NO_IMPLEMENTATION
1254 #endif // WEBDUINO_H_