Konfiguration über http
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1321 строка
36KB

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