httpd_parse.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. // Copyright 2018 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <stdlib.h>
  15. #include <sys/param.h>
  16. #include <esp_log.h>
  17. #include <esp_err.h>
  18. #include <http_parser.h>
  19. #include <esp_http_server.h>
  20. #include "esp_httpd_priv.h"
  21. #include "osal.h"
  22. static const char *TAG = "httpd_parse";
  23. typedef struct {
  24. /* Parser settings for http_parser_execute() */
  25. http_parser_settings settings;
  26. /* Request being parsed */
  27. struct httpd_req *req;
  28. /* Status of the parser describes the part of the
  29. * HTTP request packet being processed at any moment.
  30. */
  31. enum {
  32. PARSING_IDLE = 0,
  33. PARSING_URL,
  34. PARSING_HDR_FIELD,
  35. PARSING_HDR_VALUE,
  36. PARSING_BODY,
  37. PARSING_COMPLETE,
  38. PARSING_FAILED
  39. } status;
  40. /* Response error code in case of PARSING_FAILED */
  41. httpd_err_code_t error;
  42. /* For storing last callback parameters */
  43. struct {
  44. const char *at;
  45. size_t length;
  46. } last;
  47. /* State variables */
  48. bool paused; /*!< Parser is paused */
  49. size_t pre_parsed; /*!< Length of data to be skipped while parsing */
  50. size_t raw_datalen; /*!< Full length of the raw data in scratch buffer */
  51. } parser_data_t;
  52. static esp_err_t verify_url (http_parser *parser)
  53. {
  54. parser_data_t *parser_data = (parser_data_t *) parser->data;
  55. struct httpd_req *r = parser_data->req;
  56. struct httpd_req_aux *ra = r->aux;
  57. struct http_parser_url *res = &ra->url_parse_res;
  58. /* Get previous values of the parser callback arguments */
  59. const char *at = parser_data->last.at;
  60. size_t length = parser_data->last.length;
  61. if ((r->method = parser->method) < 0) {
  62. ESP_LOGW(TAG, LOG_FMT("HTTP Operation not supported"));
  63. parser_data->error = HTTPD_501_METHOD_NOT_IMPLEMENTED;
  64. return ESP_FAIL;
  65. }
  66. if (sizeof(r->uri) < (length + 1)) {
  67. ESP_LOGW(TAG, LOG_FMT("URI length (%d) greater than supported (%d)"),
  68. length, sizeof(r->uri));
  69. parser_data->error = HTTPD_414_URI_TOO_LONG;
  70. return ESP_FAIL;
  71. }
  72. /* Keep URI with terminating null character. Note URI string pointed
  73. * by 'at' is not NULL terminated, therefore use length provided by
  74. * parser while copying the URI to buffer */
  75. strlcpy((char *)r->uri, at, (length + 1));
  76. ESP_LOGD(TAG, LOG_FMT("received URI = %s"), r->uri);
  77. /* Make sure version is HTTP/1.1 */
  78. if ((parser->http_major != 1) && (parser->http_minor != 1)) {
  79. ESP_LOGW(TAG, LOG_FMT("unsupported HTTP version = %d.%d"),
  80. parser->http_major, parser->http_minor);
  81. parser_data->error = HTTPD_505_VERSION_NOT_SUPPORTED;
  82. return ESP_FAIL;
  83. }
  84. /* Parse URL and keep result for later */
  85. http_parser_url_init(res);
  86. if (http_parser_parse_url(r->uri, strlen(r->uri),
  87. r->method == HTTP_CONNECT, res)) {
  88. ESP_LOGW(TAG, LOG_FMT("http_parser_parse_url failed with errno = %d"),
  89. parser->http_errno);
  90. parser_data->error = HTTPD_400_BAD_REQUEST;
  91. return ESP_FAIL;
  92. }
  93. return ESP_OK;
  94. }
  95. /* http_parser callback on finding url in HTTP request
  96. * Will be invoked ATLEAST once every packet
  97. */
  98. static esp_err_t cb_url(http_parser *parser,
  99. const char *at, size_t length)
  100. {
  101. parser_data_t *parser_data = (parser_data_t *) parser->data;
  102. if (parser_data->status == PARSING_IDLE) {
  103. ESP_LOGD(TAG, LOG_FMT("message begin"));
  104. /* Store current values of the parser callback arguments */
  105. parser_data->last.at = at;
  106. parser_data->last.length = 0;
  107. parser_data->status = PARSING_URL;
  108. } else if (parser_data->status != PARSING_URL) {
  109. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  110. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  111. parser_data->status = PARSING_FAILED;
  112. return ESP_FAIL;
  113. }
  114. ESP_LOGD(TAG, LOG_FMT("processing url = %.*s"), length, at);
  115. /* Update length of URL string */
  116. if ((parser_data->last.length += length) > HTTPD_MAX_URI_LEN) {
  117. ESP_LOGW(TAG, LOG_FMT("URI length (%d) greater than supported (%d)"),
  118. parser_data->last.length, HTTPD_MAX_URI_LEN);
  119. parser_data->error = HTTPD_414_URI_TOO_LONG;
  120. parser_data->status = PARSING_FAILED;
  121. return ESP_FAIL;
  122. }
  123. return ESP_OK;
  124. }
  125. static esp_err_t pause_parsing(http_parser *parser, const char* at)
  126. {
  127. parser_data_t *parser_data = (parser_data_t *) parser->data;
  128. struct httpd_req *r = parser_data->req;
  129. struct httpd_req_aux *ra = r->aux;
  130. /* The length of data that was not parsed due to interruption
  131. * and hence needs to be read again later for parsing */
  132. ssize_t unparsed = parser_data->raw_datalen - (at - ra->scratch);
  133. if (unparsed < 0) {
  134. ESP_LOGE(TAG, LOG_FMT("parsing beyond valid data = %d"), -unparsed);
  135. return ESP_ERR_INVALID_STATE;
  136. }
  137. /* Push back the un-parsed data into pending buffer for
  138. * receiving again with httpd_recv_with_opt() later when
  139. * read_block() executes */
  140. if (unparsed && (unparsed != httpd_unrecv(r, at, unparsed))) {
  141. ESP_LOGE(TAG, LOG_FMT("data too large for un-recv = %d"), unparsed);
  142. return ESP_FAIL;
  143. }
  144. /* Signal http_parser to pause execution and save the maximum
  145. * possible length, of the yet un-parsed data, that may get
  146. * parsed before http_parser_execute() returns. This pre_parsed
  147. * length will be updated then to reflect the actual length
  148. * that got parsed, and must be skipped when parsing resumes */
  149. parser_data->pre_parsed = unparsed;
  150. http_parser_pause(parser, 1);
  151. parser_data->paused = true;
  152. ESP_LOGD(TAG, LOG_FMT("paused"));
  153. return ESP_OK;
  154. }
  155. static size_t continue_parsing(http_parser *parser, size_t length)
  156. {
  157. parser_data_t *data = (parser_data_t *) parser->data;
  158. /* Part of the received data may have been parsed earlier
  159. * so we must skip that before parsing resumes */
  160. length = MIN(length, data->pre_parsed);
  161. data->pre_parsed -= length;
  162. ESP_LOGD(TAG, LOG_FMT("skip pre-parsed data of size = %d"), length);
  163. http_parser_pause(parser, 0);
  164. data->paused = false;
  165. ESP_LOGD(TAG, LOG_FMT("un-paused"));
  166. return length;
  167. }
  168. /* http_parser callback on header field in HTTP request
  169. * May be invoked ATLEAST once every header field
  170. */
  171. static esp_err_t cb_header_field(http_parser *parser, const char *at, size_t length)
  172. {
  173. parser_data_t *parser_data = (parser_data_t *) parser->data;
  174. struct httpd_req *r = parser_data->req;
  175. struct httpd_req_aux *ra = r->aux;
  176. /* Check previous status */
  177. if (parser_data->status == PARSING_URL) {
  178. if (verify_url(parser) != ESP_OK) {
  179. /* verify_url would already have set the
  180. * error field of parser data, so only setting
  181. * status to failed */
  182. parser_data->status = PARSING_FAILED;
  183. return ESP_FAIL;
  184. }
  185. ESP_LOGD(TAG, LOG_FMT("headers begin"));
  186. /* Last at is set to start of scratch where headers
  187. * will be received next */
  188. parser_data->last.at = ra->scratch;
  189. parser_data->last.length = 0;
  190. parser_data->status = PARSING_HDR_FIELD;
  191. /* Stop parsing for now and give control to process */
  192. if (pause_parsing(parser, at) != ESP_OK) {
  193. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  194. parser_data->status = PARSING_FAILED;
  195. return ESP_FAIL;
  196. }
  197. } else if (parser_data->status == PARSING_HDR_VALUE) {
  198. /* Overwrite terminator (CRLFs) following last header
  199. * (key: value) pair with null characters */
  200. char *term_start = (char *)parser_data->last.at + parser_data->last.length;
  201. memset(term_start, '\0', at - term_start);
  202. /* Store current values of the parser callback arguments */
  203. parser_data->last.at = at;
  204. parser_data->last.length = 0;
  205. parser_data->status = PARSING_HDR_FIELD;
  206. /* Increment header count */
  207. ra->req_hdrs_count++;
  208. } else if (parser_data->status != PARSING_HDR_FIELD) {
  209. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  210. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  211. parser_data->status = PARSING_FAILED;
  212. return ESP_FAIL;
  213. }
  214. ESP_LOGD(TAG, LOG_FMT("processing field = %.*s"), length, at);
  215. /* Update length of header string */
  216. parser_data->last.length += length;
  217. return ESP_OK;
  218. }
  219. /* http_parser callback on header value in HTTP request.
  220. * May be invoked ATLEAST once every header value
  221. */
  222. static esp_err_t cb_header_value(http_parser *parser, const char *at, size_t length)
  223. {
  224. parser_data_t *parser_data = (parser_data_t *) parser->data;
  225. /* Check previous status */
  226. if (parser_data->status == PARSING_HDR_FIELD) {
  227. /* Store current values of the parser callback arguments */
  228. parser_data->last.at = at;
  229. parser_data->last.length = 0;
  230. parser_data->status = PARSING_HDR_VALUE;
  231. if (length == 0) {
  232. /* As per behavior of http_parser, when length > 0,
  233. * `at` points to the start of CRLF. But, in the
  234. * case when header value is empty (zero length),
  235. * then `at` points to the position right after
  236. * the CRLF. Since for our purpose we need `last.at`
  237. * to point to exactly where the CRLF starts, it
  238. * needs to be adjusted by the right offset */
  239. char *at_adj = (char *)parser_data->last.at;
  240. /* Find the end of header field string */
  241. while (*(--at_adj) != ':');
  242. /* Now skip leading spaces' */
  243. while (*(++at_adj) == ' ');
  244. /* Now we are at the right position */
  245. parser_data->last.at = at_adj;
  246. }
  247. } else if (parser_data->status != PARSING_HDR_VALUE) {
  248. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  249. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  250. parser_data->status = PARSING_FAILED;
  251. return ESP_FAIL;
  252. }
  253. ESP_LOGD(TAG, LOG_FMT("processing value = %.*s"), length, at);
  254. /* Update length of header string */
  255. parser_data->last.length += length;
  256. return ESP_OK;
  257. }
  258. /* http_parser callback on completing headers in HTTP request.
  259. * Will be invoked ONLY once every packet
  260. */
  261. static esp_err_t cb_headers_complete(http_parser *parser)
  262. {
  263. parser_data_t *parser_data = (parser_data_t *) parser->data;
  264. struct httpd_req *r = parser_data->req;
  265. struct httpd_req_aux *ra = r->aux;
  266. /* Check previous status */
  267. if (parser_data->status == PARSING_URL) {
  268. ESP_LOGD(TAG, LOG_FMT("no headers"));
  269. if (verify_url(parser) != ESP_OK) {
  270. /* verify_url would already have set the
  271. * error field of parser data, so only setting
  272. * status to failed */
  273. parser_data->status = PARSING_FAILED;
  274. return ESP_FAIL;
  275. }
  276. } else if (parser_data->status == PARSING_HDR_VALUE) {
  277. /* Locate end of last header */
  278. char *at = (char *)parser_data->last.at + parser_data->last.length;
  279. /* Check if there is data left to parse. This value should
  280. * at least be equal to the number of line terminators, i.e. 2 */
  281. ssize_t remaining_length = parser_data->raw_datalen - (at - ra->scratch);
  282. if (remaining_length < 2) {
  283. ESP_LOGE(TAG, LOG_FMT("invalid length of data remaining to be parsed"));
  284. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  285. parser_data->status = PARSING_FAILED;
  286. return ESP_FAIL;
  287. }
  288. /* Locate end of headers section by skipping the remaining
  289. * two line terminators. No assumption is made here about the
  290. * termination sequence used apart from the necessity that it
  291. * must end with an LF, because:
  292. * 1) some clients may send non standard LFs instead of
  293. * CRLFs for indicating termination.
  294. * 2) it is the responsibility of http_parser to check
  295. * that the termination is either CRLF or LF and
  296. * not any other sequence */
  297. unsigned short remaining_terminators = 2;
  298. while (remaining_length-- && remaining_terminators) {
  299. if (*at == '\n') {
  300. remaining_terminators--;
  301. }
  302. /* Overwrite termination characters with null */
  303. *(at++) = '\0';
  304. }
  305. if (remaining_terminators) {
  306. ESP_LOGE(TAG, LOG_FMT("incomplete termination of headers"));
  307. parser_data->error = HTTPD_400_BAD_REQUEST;
  308. parser_data->status = PARSING_FAILED;
  309. return ESP_FAIL;
  310. }
  311. /* Place the parser ptr right after the end of headers section */
  312. parser_data->last.at = at;
  313. /* Increment header count */
  314. ra->req_hdrs_count++;
  315. } else {
  316. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  317. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  318. parser_data->status = PARSING_FAILED;
  319. return ESP_FAIL;
  320. }
  321. /* In absence of body/chunked encoding, http_parser sets content_len to -1 */
  322. r->content_len = ((int)parser->content_length != -1 ?
  323. parser->content_length : 0);
  324. ESP_LOGD(TAG, LOG_FMT("bytes read = %d"), parser->nread);
  325. ESP_LOGD(TAG, LOG_FMT("content length = %zu"), r->content_len);
  326. /* Handle upgrade requests - only WebSocket is supported for now */
  327. if (parser->upgrade) {
  328. #ifdef CONFIG_HTTPD_WS_SUPPORT
  329. ESP_LOGD(TAG, LOG_FMT("Got an upgrade request"));
  330. /* If there's no "Upgrade" header field, then it's not WebSocket. */
  331. char ws_upgrade_hdr_val[] = "websocket";
  332. if (httpd_req_get_hdr_value_str(r, "Upgrade", ws_upgrade_hdr_val, sizeof(ws_upgrade_hdr_val)) != ESP_OK) {
  333. ESP_LOGW(TAG, LOG_FMT("Upgrade header does not match the length of \"websocket\""));
  334. parser_data->error = HTTPD_400_BAD_REQUEST;
  335. parser_data->status = PARSING_FAILED;
  336. return ESP_FAIL;
  337. }
  338. /* If "Upgrade" field's key is not "websocket", then we should also forget about it. */
  339. if (strcasecmp("websocket", ws_upgrade_hdr_val) != 0) {
  340. ESP_LOGW(TAG, LOG_FMT("Upgrade header found but it's %s"), ws_upgrade_hdr_val);
  341. parser_data->error = HTTPD_400_BAD_REQUEST;
  342. parser_data->status = PARSING_FAILED;
  343. return ESP_FAIL;
  344. }
  345. /* Now set handshake flag to true */
  346. ra->ws_handshake_detect = true;
  347. #else
  348. ESP_LOGD(TAG, LOG_FMT("WS functions has been disabled, Upgrade request is not supported."));
  349. parser_data->error = HTTPD_400_BAD_REQUEST;
  350. parser_data->status = PARSING_FAILED;
  351. return ESP_FAIL;
  352. #endif
  353. }
  354. parser_data->status = PARSING_BODY;
  355. ra->remaining_len = r->content_len;
  356. return ESP_OK;
  357. }
  358. /* Last http_parser callback if body present in HTTP request.
  359. * Will be invoked ONLY once every packet
  360. */
  361. static esp_err_t cb_on_body(http_parser *parser, const char *at, size_t length)
  362. {
  363. parser_data_t *parser_data = (parser_data_t *) parser->data;
  364. /* Check previous status */
  365. if (parser_data->status != PARSING_BODY) {
  366. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  367. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  368. parser_data->status = PARSING_FAILED;
  369. return ESP_FAIL;
  370. }
  371. /* Pause parsing so that if part of another packet
  372. * is in queue then it doesn't get parsed, which
  373. * may reset the parser state and cause current
  374. * request packet to be lost */
  375. if (pause_parsing(parser, at) != ESP_OK) {
  376. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  377. parser_data->status = PARSING_FAILED;
  378. return ESP_FAIL;
  379. }
  380. parser_data->last.at = 0;
  381. parser_data->last.length = 0;
  382. parser_data->status = PARSING_COMPLETE;
  383. ESP_LOGD(TAG, LOG_FMT("body begins"));
  384. return ESP_OK;
  385. }
  386. /* Last http_parser callback if body absent in HTTP request.
  387. * Will be invoked ONLY once every packet
  388. */
  389. static esp_err_t cb_no_body(http_parser *parser)
  390. {
  391. parser_data_t *parser_data = (parser_data_t *) parser->data;
  392. /* Check previous status */
  393. if (parser_data->status == PARSING_URL) {
  394. ESP_LOGD(TAG, LOG_FMT("no headers"));
  395. if (verify_url(parser) != ESP_OK) {
  396. /* verify_url would already have set the
  397. * error field of parser data, so only setting
  398. * status to failed */
  399. parser_data->status = PARSING_FAILED;
  400. return ESP_FAIL;
  401. }
  402. } else if (parser_data->status != PARSING_BODY) {
  403. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  404. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  405. parser_data->status = PARSING_FAILED;
  406. return ESP_FAIL;
  407. }
  408. /* Pause parsing so that if part of another packet
  409. * is in queue then it doesn't get parsed, which
  410. * may reset the parser state and cause current
  411. * request packet to be lost */
  412. if (pause_parsing(parser, parser_data->last.at) != ESP_OK) {
  413. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  414. parser_data->status = PARSING_FAILED;
  415. return ESP_FAIL;
  416. }
  417. parser_data->last.at = 0;
  418. parser_data->last.length = 0;
  419. parser_data->status = PARSING_COMPLETE;
  420. ESP_LOGD(TAG, LOG_FMT("message complete"));
  421. return ESP_OK;
  422. }
  423. static int read_block(httpd_req_t *req, size_t offset, size_t length)
  424. {
  425. struct httpd_req_aux *raux = req->aux;
  426. /* Limits the read to scratch buffer size */
  427. ssize_t buf_len = MIN(length, (sizeof(raux->scratch) - offset));
  428. if (buf_len <= 0) {
  429. return 0;
  430. }
  431. /* Receive data into buffer. If data is pending (from unrecv) then return
  432. * immediately after receiving pending data, as pending data may just complete
  433. * this request packet. */
  434. int nbytes = httpd_recv_with_opt(req, raux->scratch + offset, buf_len, true);
  435. if (nbytes < 0) {
  436. ESP_LOGD(TAG, LOG_FMT("error in httpd_recv"));
  437. /* If timeout occurred allow the
  438. * situation to be handled */
  439. if (nbytes == HTTPD_SOCK_ERR_TIMEOUT) {
  440. /* Invoke error handler which may return ESP_OK
  441. * to signal for retrying call to recv(), else it may
  442. * return ESP_FAIL to signal for closure of socket */
  443. return (httpd_req_handle_err(req, HTTPD_408_REQ_TIMEOUT) == ESP_OK) ?
  444. HTTPD_SOCK_ERR_TIMEOUT : HTTPD_SOCK_ERR_FAIL;
  445. }
  446. /* Some socket error occurred. Return failure
  447. * to force closure of underlying socket.
  448. * Error message is not sent as socket may not
  449. * be valid anymore */
  450. return HTTPD_SOCK_ERR_FAIL;
  451. } else if (nbytes == 0) {
  452. ESP_LOGD(TAG, LOG_FMT("connection closed"));
  453. /* Connection closed by client so no
  454. * need to send error response */
  455. return HTTPD_SOCK_ERR_FAIL;
  456. }
  457. ESP_LOGD(TAG, LOG_FMT("received HTTP request block size = %d"), nbytes);
  458. return nbytes;
  459. }
  460. static int parse_block(http_parser *parser, size_t offset, size_t length)
  461. {
  462. parser_data_t *data = (parser_data_t *)(parser->data);
  463. httpd_req_t *req = data->req;
  464. struct httpd_req_aux *raux = req->aux;
  465. size_t nparsed = 0;
  466. if (!length) {
  467. /* Parsing is still happening but nothing to
  468. * parse means no more space left on buffer,
  469. * therefore it can be inferred that the
  470. * request URI/header must be too long */
  471. ESP_LOGW(TAG, LOG_FMT("request URI/header too long"));
  472. switch (data->status) {
  473. case PARSING_URL:
  474. data->error = HTTPD_414_URI_TOO_LONG;
  475. break;
  476. case PARSING_HDR_FIELD:
  477. case PARSING_HDR_VALUE:
  478. data->error = HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE;
  479. break;
  480. default:
  481. ESP_LOGE(TAG, LOG_FMT("unexpected state"));
  482. data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  483. break;
  484. }
  485. data->status = PARSING_FAILED;
  486. return -1;
  487. }
  488. /* Un-pause the parsing if paused */
  489. if (data->paused) {
  490. nparsed = continue_parsing(parser, length);
  491. length -= nparsed;
  492. offset += nparsed;
  493. if (!length) {
  494. return nparsed;
  495. }
  496. }
  497. /* Execute http_parser */
  498. nparsed = http_parser_execute(parser, &data->settings,
  499. raux->scratch + offset, length);
  500. /* Check state */
  501. if (data->status == PARSING_FAILED) {
  502. /* It is expected that the error field of
  503. * parser data should have been set by now */
  504. ESP_LOGW(TAG, LOG_FMT("parsing failed"));
  505. return -1;
  506. } else if (data->paused) {
  507. /* Update the value of pre_parsed which was set when
  508. * pause_parsing() was called. (length - nparsed) is
  509. * the length of the data that will need to be parsed
  510. * again later and hence must be deducted from the
  511. * pre_parsed length */
  512. data->pre_parsed -= (length - nparsed);
  513. return 0;
  514. } else if (nparsed != length) {
  515. /* http_parser error */
  516. data->error = HTTPD_400_BAD_REQUEST;
  517. data->status = PARSING_FAILED;
  518. ESP_LOGW(TAG, LOG_FMT("incomplete (%d/%d) with parser error = %d"),
  519. nparsed, length, parser->http_errno);
  520. return -1;
  521. }
  522. /* Return with the total length of the request packet
  523. * that has been parsed till now */
  524. ESP_LOGD(TAG, LOG_FMT("parsed block size = %d"), offset + nparsed);
  525. return offset + nparsed;
  526. }
  527. static void parse_init(httpd_req_t *r, http_parser *parser, parser_data_t *data)
  528. {
  529. /* Initialize parser data */
  530. memset(data, 0, sizeof(parser_data_t));
  531. data->req = r;
  532. /* Initialize parser */
  533. http_parser_init(parser, HTTP_REQUEST);
  534. parser->data = (void *)data;
  535. /* Initialize parser settings */
  536. http_parser_settings_init(&data->settings);
  537. /* Set parser callbacks */
  538. data->settings.on_url = cb_url;
  539. data->settings.on_header_field = cb_header_field;
  540. data->settings.on_header_value = cb_header_value;
  541. data->settings.on_headers_complete = cb_headers_complete;
  542. data->settings.on_body = cb_on_body;
  543. data->settings.on_message_complete = cb_no_body;
  544. }
  545. /* Function that receives TCP data and runs parser on it
  546. */
  547. static esp_err_t httpd_parse_req(struct httpd_data *hd)
  548. {
  549. httpd_req_t *r = &hd->hd_req;
  550. int blk_len, offset;
  551. http_parser parser;
  552. parser_data_t parser_data;
  553. /* Initialize parser */
  554. parse_init(r, &parser, &parser_data);
  555. /* Set offset to start of scratch buffer */
  556. offset = 0;
  557. do {
  558. /* Read block into scratch buffer */
  559. if ((blk_len = read_block(r, offset, PARSER_BLOCK_SIZE)) < 0) {
  560. if (blk_len == HTTPD_SOCK_ERR_TIMEOUT) {
  561. /* Retry read in case of non-fatal timeout error.
  562. * read_block() ensures that the timeout error is
  563. * handled properly so that this doesn't get stuck
  564. * in an infinite loop */
  565. continue;
  566. }
  567. /* If not HTTPD_SOCK_ERR_TIMEOUT, returned error must
  568. * be HTTPD_SOCK_ERR_FAIL which means we need to return
  569. * failure and thereby close the underlying socket */
  570. return ESP_FAIL;
  571. }
  572. /* This is used by the callbacks to track
  573. * data usage of the buffer */
  574. parser_data.raw_datalen = blk_len + offset;
  575. /* Parse data block from buffer */
  576. if ((offset = parse_block(&parser, offset, blk_len)) < 0) {
  577. /* HTTP error occurred.
  578. * Send error code as response status and
  579. * invoke error handler */
  580. return httpd_req_handle_err(r, parser_data.error);
  581. }
  582. } while (parser_data.status != PARSING_COMPLETE);
  583. ESP_LOGD(TAG, LOG_FMT("parsing complete"));
  584. return httpd_uri(hd);
  585. }
  586. static void init_req(httpd_req_t *r, httpd_config_t *config)
  587. {
  588. r->handle = 0;
  589. r->method = 0;
  590. memset((char*)r->uri, 0, sizeof(r->uri));
  591. r->content_len = 0;
  592. r->aux = 0;
  593. r->user_ctx = 0;
  594. r->sess_ctx = 0;
  595. r->free_ctx = 0;
  596. r->ignore_sess_ctx_changes = 0;
  597. }
  598. static void init_req_aux(struct httpd_req_aux *ra, httpd_config_t *config)
  599. {
  600. ra->sd = 0;
  601. memset(ra->scratch, 0, sizeof(ra->scratch));
  602. ra->remaining_len = 0;
  603. ra->status = 0;
  604. ra->content_type = 0;
  605. ra->first_chunk_sent = 0;
  606. ra->req_hdrs_count = 0;
  607. ra->resp_hdrs_count = 0;
  608. #if CONFIG_HTTPD_WS_SUPPORT
  609. ra->ws_handshake_detect = false;
  610. #endif
  611. memset(ra->resp_hdrs, 0, config->max_resp_headers * sizeof(struct resp_hdr));
  612. }
  613. static void httpd_req_cleanup(httpd_req_t *r)
  614. {
  615. struct httpd_req_aux *ra = r->aux;
  616. /* Check if the context has changed and needs to be cleared */
  617. if ((r->ignore_sess_ctx_changes == false) && (ra->sd->ctx != r->sess_ctx)) {
  618. httpd_sess_free_ctx(ra->sd->ctx, ra->sd->free_ctx);
  619. }
  620. #if CONFIG_HTTPD_WS_SUPPORT
  621. /* Close the socket when a WebSocket Close request is received */
  622. if (ra->sd->ws_close) {
  623. ESP_LOGD(TAG, LOG_FMT("Try closing WS connection at FD: %d"), ra->sd->fd);
  624. httpd_sess_trigger_close(r->handle, ra->sd->fd);
  625. }
  626. #endif
  627. /* Retrieve session info from the request into the socket database. */
  628. ra->sd->ctx = r->sess_ctx;
  629. ra->sd->free_ctx = r->free_ctx;
  630. ra->sd->ignore_sess_ctx_changes = r->ignore_sess_ctx_changes;
  631. /* Clear out the request and request_aux structures */
  632. ra->sd = NULL;
  633. r->handle = NULL;
  634. r->aux = NULL;
  635. }
  636. /* Function that processes incoming TCP data and
  637. * updates the http request data httpd_req_t
  638. */
  639. esp_err_t httpd_req_new(struct httpd_data *hd, struct sock_db *sd)
  640. {
  641. httpd_req_t *r = &hd->hd_req;
  642. init_req(r, &hd->config);
  643. init_req_aux(&hd->hd_req_aux, &hd->config);
  644. r->handle = hd;
  645. r->aux = &hd->hd_req_aux;
  646. /* Associate the request to the socket */
  647. struct httpd_req_aux *ra = r->aux;
  648. ra->sd = sd;
  649. /* Set defaults */
  650. ra->status = (char *)HTTPD_200;
  651. ra->content_type = (char *)HTTPD_TYPE_TEXT;
  652. ra->first_chunk_sent = false;
  653. /* Copy session info to the request */
  654. r->sess_ctx = sd->ctx;
  655. r->free_ctx = sd->free_ctx;
  656. r->ignore_sess_ctx_changes = sd->ignore_sess_ctx_changes;
  657. esp_err_t ret;
  658. #ifdef CONFIG_HTTPD_WS_SUPPORT
  659. /* Handle WebSocket */
  660. ESP_LOGD(TAG, LOG_FMT("New request, has WS? %s, sd->ws_handler valid? %s, sd->ws_close? %s"),
  661. sd->ws_handshake_done ? "Yes" : "No",
  662. sd->ws_handler != NULL ? "Yes" : "No",
  663. sd->ws_close ? "Yes" : "No");
  664. if (sd->ws_handshake_done && sd->ws_handler != NULL) {
  665. ESP_LOGD(TAG, LOG_FMT("New WS request from existing socket"));
  666. ret = httpd_ws_get_frame_type(r);
  667. /* Stop and return here immediately if it's a CLOSE frame */
  668. if (ra->ws_type == HTTPD_WS_TYPE_CLOSE) {
  669. sd->ws_close = true;
  670. return ret;
  671. }
  672. /* Ignore PONG frame, as this is a server */
  673. if (ra->ws_type == HTTPD_WS_TYPE_PONG) {
  674. return ret;
  675. }
  676. /* Call handler if it's a non-control frame */
  677. if (ret == ESP_OK && ra->ws_type < HTTPD_WS_TYPE_CLOSE) {
  678. ret = sd->ws_handler(r);
  679. }
  680. if (ret != ESP_OK) {
  681. httpd_req_cleanup(r);
  682. }
  683. return ret;
  684. }
  685. #endif
  686. /* Parse request */
  687. ret = httpd_parse_req(hd);
  688. if (ret != ESP_OK) {
  689. httpd_req_cleanup(r);
  690. }
  691. return ret;
  692. }
  693. /* Function that resets the http request data
  694. */
  695. esp_err_t httpd_req_delete(struct httpd_data *hd)
  696. {
  697. httpd_req_t *r = &hd->hd_req;
  698. struct httpd_req_aux *ra = r->aux;
  699. /* Finish off reading any pending/leftover data */
  700. while (ra->remaining_len) {
  701. /* Any length small enough not to overload the stack, but large
  702. * enough to finish off the buffers fast */
  703. char dummy[CONFIG_HTTPD_PURGE_BUF_LEN];
  704. int recv_len = MIN(sizeof(dummy), ra->remaining_len);
  705. recv_len = httpd_req_recv(r, dummy, recv_len);
  706. if (recv_len < 0) {
  707. httpd_req_cleanup(r);
  708. return ESP_FAIL;
  709. }
  710. ESP_LOGD(TAG, LOG_FMT("purging data size : %d bytes"), recv_len);
  711. #ifdef CONFIG_HTTPD_LOG_PURGE_DATA
  712. /* Enabling this will log discarded binary HTTP content data at
  713. * Debug level. For large content data this may not be desirable
  714. * as it will clutter the log */
  715. ESP_LOGD(TAG, "================= PURGED DATA =================");
  716. ESP_LOG_BUFFER_HEX_LEVEL(TAG, dummy, recv_len, ESP_LOG_DEBUG);
  717. ESP_LOGD(TAG, "===============================================");
  718. #endif
  719. }
  720. httpd_req_cleanup(r);
  721. return ESP_OK;
  722. }
  723. /* Validates the request to prevent users from calling APIs, that are to
  724. * be called only inside URI handler, outside the handler context
  725. */
  726. bool httpd_validate_req_ptr(httpd_req_t *r)
  727. {
  728. if (r) {
  729. struct httpd_data *hd = (struct httpd_data *) r->handle;
  730. if (hd) {
  731. /* Check if this function is running in the context of
  732. * the correct httpd server thread */
  733. if (httpd_os_thread_handle() == hd->hd_td.handle) {
  734. return true;
  735. }
  736. }
  737. }
  738. return false;
  739. }
  740. /* Helper function to get a URL query tag from a query string of the type param1=val1&param2=val2 */
  741. esp_err_t httpd_query_key_value(const char *qry_str, const char *key, char *val, size_t val_size)
  742. {
  743. if (qry_str == NULL || key == NULL || val == NULL) {
  744. return ESP_ERR_INVALID_ARG;
  745. }
  746. const char *qry_ptr = qry_str;
  747. const size_t buf_len = val_size;
  748. while (strlen(qry_ptr)) {
  749. /* Search for the '=' character. Else, it would mean
  750. * that the parameter is invalid */
  751. const char *val_ptr = strchr(qry_ptr, '=');
  752. if (!val_ptr) {
  753. break;
  754. }
  755. size_t offset = val_ptr - qry_ptr;
  756. /* If the key, does not match, continue searching.
  757. * Compare lengths first as key from url is not
  758. * null terminated (has '=' in the end) */
  759. if ((offset != strlen(key)) ||
  760. (strncasecmp(qry_ptr, key, offset))) {
  761. /* Get the name=val string. Multiple name=value pairs
  762. * are separated by '&' */
  763. qry_ptr = strchr(val_ptr, '&');
  764. if (!qry_ptr) {
  765. break;
  766. }
  767. qry_ptr++;
  768. continue;
  769. }
  770. /* Locate start of next query */
  771. qry_ptr = strchr(++val_ptr, '&');
  772. /* Or this could be the last query, in which
  773. * case get to the end of query string */
  774. if (!qry_ptr) {
  775. qry_ptr = val_ptr + strlen(val_ptr);
  776. }
  777. /* Update value length, including one byte for null */
  778. val_size = qry_ptr - val_ptr + 1;
  779. /* Copy value to the caller's buffer. */
  780. strlcpy(val, val_ptr, MIN(val_size, buf_len));
  781. /* If buffer length is smaller than needed, return truncation error */
  782. if (buf_len < val_size) {
  783. return ESP_ERR_HTTPD_RESULT_TRUNC;
  784. }
  785. return ESP_OK;
  786. }
  787. ESP_LOGD(TAG, LOG_FMT("key %s not found"), key);
  788. return ESP_ERR_NOT_FOUND;
  789. }
  790. size_t httpd_req_get_url_query_len(httpd_req_t *r)
  791. {
  792. if (r == NULL) {
  793. return 0;
  794. }
  795. if (!httpd_valid_req(r)) {
  796. return 0;
  797. }
  798. struct httpd_req_aux *ra = r->aux;
  799. struct http_parser_url *res = &ra->url_parse_res;
  800. /* Check if query field is present in the URL */
  801. if (res->field_set & (1 << UF_QUERY)) {
  802. return res->field_data[UF_QUERY].len;
  803. }
  804. return 0;
  805. }
  806. esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len)
  807. {
  808. if (r == NULL || buf == NULL) {
  809. return ESP_ERR_INVALID_ARG;
  810. }
  811. if (!httpd_valid_req(r)) {
  812. return ESP_ERR_HTTPD_INVALID_REQ;
  813. }
  814. struct httpd_req_aux *ra = r->aux;
  815. struct http_parser_url *res = &ra->url_parse_res;
  816. /* Check if query field is present in the URL */
  817. if (res->field_set & (1 << UF_QUERY)) {
  818. const char *qry = r->uri + res->field_data[UF_QUERY].off;
  819. /* Minimum required buffer len for keeping
  820. * null terminated query string */
  821. size_t min_buf_len = res->field_data[UF_QUERY].len + 1;
  822. strlcpy(buf, qry, MIN(buf_len, min_buf_len));
  823. if (buf_len < min_buf_len) {
  824. return ESP_ERR_HTTPD_RESULT_TRUNC;
  825. }
  826. return ESP_OK;
  827. }
  828. return ESP_ERR_NOT_FOUND;
  829. }
  830. /* Get the length of the value string of a header request field */
  831. size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field)
  832. {
  833. if (r == NULL || field == NULL) {
  834. return 0;
  835. }
  836. if (!httpd_valid_req(r)) {
  837. return 0;
  838. }
  839. struct httpd_req_aux *ra = r->aux;
  840. const char *hdr_ptr = ra->scratch; /*!< Request headers are kept in scratch buffer */
  841. unsigned count = ra->req_hdrs_count; /*!< Count set during parsing */
  842. while (count--) {
  843. /* Search for the ':' character. Else, it would mean
  844. * that the field is invalid
  845. */
  846. const char *val_ptr = strchr(hdr_ptr, ':');
  847. if (!val_ptr) {
  848. break;
  849. }
  850. /* If the field, does not match, continue searching.
  851. * Compare lengths first as field from header is not
  852. * null terminated (has ':' in the end).
  853. */
  854. if ((val_ptr - hdr_ptr != strlen(field)) ||
  855. (strncasecmp(hdr_ptr, field, strlen(field)))) {
  856. if (count) {
  857. /* Jump to end of header field-value string */
  858. hdr_ptr = 1 + strchr(hdr_ptr, '\0');
  859. /* Skip all null characters (with which the line
  860. * terminators had been overwritten) */
  861. while (*hdr_ptr == '\0') {
  862. hdr_ptr++;
  863. }
  864. }
  865. continue;
  866. }
  867. /* Skip ':' */
  868. val_ptr++;
  869. /* Skip preceding space */
  870. while ((*val_ptr != '\0') && (*val_ptr == ' ')) {
  871. val_ptr++;
  872. }
  873. return strlen(val_ptr);
  874. }
  875. return 0;
  876. }
  877. /* Get the value of a field from the request headers */
  878. esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size)
  879. {
  880. if (r == NULL || field == NULL) {
  881. return ESP_ERR_INVALID_ARG;
  882. }
  883. if (!httpd_valid_req(r)) {
  884. return ESP_ERR_HTTPD_INVALID_REQ;
  885. }
  886. struct httpd_req_aux *ra = r->aux;
  887. const char *hdr_ptr = ra->scratch; /*!< Request headers are kept in scratch buffer */
  888. unsigned count = ra->req_hdrs_count; /*!< Count set during parsing */
  889. const size_t buf_len = val_size;
  890. while (count--) {
  891. /* Search for the ':' character. Else, it would mean
  892. * that the field is invalid
  893. */
  894. const char *val_ptr = strchr(hdr_ptr, ':');
  895. if (!val_ptr) {
  896. break;
  897. }
  898. /* If the field, does not match, continue searching.
  899. * Compare lengths first as field from header is not
  900. * null terminated (has ':' in the end).
  901. */
  902. if ((val_ptr - hdr_ptr != strlen(field)) ||
  903. (strncasecmp(hdr_ptr, field, strlen(field)))) {
  904. if (count) {
  905. /* Jump to end of header field-value string */
  906. hdr_ptr = 1 + strchr(hdr_ptr, '\0');
  907. /* Skip all null characters (with which the line
  908. * terminators had been overwritten) */
  909. while (*hdr_ptr == '\0') {
  910. hdr_ptr++;
  911. }
  912. }
  913. continue;
  914. }
  915. /* Skip ':' */
  916. val_ptr++;
  917. /* Skip preceding space */
  918. while ((*val_ptr != '\0') && (*val_ptr == ' ')) {
  919. val_ptr++;
  920. }
  921. /* Get the NULL terminated value and copy it to the caller's buffer. */
  922. strlcpy(val, val_ptr, buf_len);
  923. /* Update value length, including one byte for null */
  924. val_size = strlen(val_ptr) + 1;
  925. /* If buffer length is smaller than needed, return truncation error */
  926. if (buf_len < val_size) {
  927. return ESP_ERR_HTTPD_RESULT_TRUNC;
  928. }
  929. return ESP_OK;
  930. }
  931. return ESP_ERR_NOT_FOUND;
  932. }