httpd_parse.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. /*
  2. * SPDX-FileCopyrightText: 2018-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stdlib.h>
  7. #include <sys/param.h>
  8. #include <esp_log.h>
  9. #include <esp_err.h>
  10. #include <http_parser.h>
  11. #include <esp_http_server.h>
  12. #include "esp_httpd_priv.h"
  13. #include "osal.h"
  14. static const char *TAG = "httpd_parse";
  15. typedef struct {
  16. /* Parser settings for http_parser_execute() */
  17. http_parser_settings settings;
  18. /* Request being parsed */
  19. struct httpd_req *req;
  20. /* Status of the parser describes the part of the
  21. * HTTP request packet being processed at any moment.
  22. */
  23. enum {
  24. PARSING_IDLE = 0,
  25. PARSING_URL,
  26. PARSING_HDR_FIELD,
  27. PARSING_HDR_VALUE,
  28. PARSING_BODY,
  29. PARSING_COMPLETE,
  30. PARSING_FAILED
  31. } status;
  32. /* Response error code in case of PARSING_FAILED */
  33. httpd_err_code_t error;
  34. /* For storing last callback parameters */
  35. struct {
  36. const char *at;
  37. size_t length;
  38. } last;
  39. /* State variables */
  40. bool paused; /*!< Parser is paused */
  41. size_t pre_parsed; /*!< Length of data to be skipped while parsing */
  42. size_t raw_datalen; /*!< Full length of the raw data in scratch buffer */
  43. } parser_data_t;
  44. static esp_err_t verify_url (http_parser *parser)
  45. {
  46. parser_data_t *parser_data = (parser_data_t *) parser->data;
  47. struct httpd_req *r = parser_data->req;
  48. struct httpd_req_aux *ra = r->aux;
  49. struct http_parser_url *res = &ra->url_parse_res;
  50. /* Get previous values of the parser callback arguments */
  51. const char *at = parser_data->last.at;
  52. size_t length = parser_data->last.length;
  53. r->method = parser->method;
  54. if (r->method < 0) {
  55. ESP_LOGW(TAG, LOG_FMT("HTTP method not supported (%d)"), r->method);
  56. parser_data->error = HTTPD_501_METHOD_NOT_IMPLEMENTED;
  57. return ESP_FAIL;
  58. }
  59. if (sizeof(r->uri) < (length + 1)) {
  60. ESP_LOGW(TAG, LOG_FMT("URI length (%d) greater than supported (%d)"),
  61. length, sizeof(r->uri));
  62. parser_data->error = HTTPD_414_URI_TOO_LONG;
  63. return ESP_FAIL;
  64. }
  65. /* Keep URI with terminating null character. Note URI string pointed
  66. * by 'at' is not NULL terminated, therefore use length provided by
  67. * parser while copying the URI to buffer */
  68. strlcpy((char *)r->uri, at, (length + 1));
  69. ESP_LOGD(TAG, LOG_FMT("received URI = %s"), r->uri);
  70. /* Make sure version is HTTP/1.1 */
  71. if ((parser->http_major != 1) && (parser->http_minor != 1)) {
  72. ESP_LOGW(TAG, LOG_FMT("unsupported HTTP version = %d.%d"),
  73. parser->http_major, parser->http_minor);
  74. parser_data->error = HTTPD_505_VERSION_NOT_SUPPORTED;
  75. return ESP_FAIL;
  76. }
  77. /* Parse URL and keep result for later */
  78. http_parser_url_init(res);
  79. if (http_parser_parse_url(r->uri, strlen(r->uri),
  80. r->method == HTTP_CONNECT, res)) {
  81. ESP_LOGW(TAG, LOG_FMT("http_parser_parse_url failed with errno = %d"),
  82. parser->http_errno);
  83. parser_data->error = HTTPD_400_BAD_REQUEST;
  84. return ESP_FAIL;
  85. }
  86. return ESP_OK;
  87. }
  88. /* http_parser callback on finding url in HTTP request
  89. * Will be invoked ATLEAST once every packet
  90. */
  91. static esp_err_t cb_url(http_parser *parser,
  92. const char *at, size_t length)
  93. {
  94. parser_data_t *parser_data = (parser_data_t *) parser->data;
  95. if (parser_data->status == PARSING_IDLE) {
  96. ESP_LOGD(TAG, LOG_FMT("message begin"));
  97. /* Store current values of the parser callback arguments */
  98. parser_data->last.at = at;
  99. parser_data->last.length = 0;
  100. parser_data->status = PARSING_URL;
  101. } else if (parser_data->status != PARSING_URL) {
  102. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  103. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  104. parser_data->status = PARSING_FAILED;
  105. return ESP_FAIL;
  106. }
  107. ESP_LOGD(TAG, LOG_FMT("processing url = %.*s"), length, at);
  108. /* Update length of URL string */
  109. if ((parser_data->last.length += length) > HTTPD_MAX_URI_LEN) {
  110. ESP_LOGW(TAG, LOG_FMT("URI length (%d) greater than supported (%d)"),
  111. parser_data->last.length, HTTPD_MAX_URI_LEN);
  112. parser_data->error = HTTPD_414_URI_TOO_LONG;
  113. parser_data->status = PARSING_FAILED;
  114. return ESP_FAIL;
  115. }
  116. return ESP_OK;
  117. }
  118. static esp_err_t pause_parsing(http_parser *parser, const char* at)
  119. {
  120. parser_data_t *parser_data = (parser_data_t *) parser->data;
  121. struct httpd_req *r = parser_data->req;
  122. struct httpd_req_aux *ra = r->aux;
  123. /* The length of data that was not parsed due to interruption
  124. * and hence needs to be read again later for parsing */
  125. ssize_t unparsed = parser_data->raw_datalen - (at - ra->scratch);
  126. if (unparsed < 0) {
  127. ESP_LOGE(TAG, LOG_FMT("parsing beyond valid data = %d"), -unparsed);
  128. return ESP_ERR_INVALID_STATE;
  129. }
  130. /* Push back the un-parsed data into pending buffer for
  131. * receiving again with httpd_recv_with_opt() later when
  132. * read_block() executes */
  133. if (unparsed && (unparsed != httpd_unrecv(r, at, unparsed))) {
  134. ESP_LOGE(TAG, LOG_FMT("data too large for un-recv = %d"), unparsed);
  135. return ESP_FAIL;
  136. }
  137. /* Signal http_parser to pause execution and save the maximum
  138. * possible length, of the yet un-parsed data, that may get
  139. * parsed before http_parser_execute() returns. This pre_parsed
  140. * length will be updated then to reflect the actual length
  141. * that got parsed, and must be skipped when parsing resumes */
  142. parser_data->pre_parsed = unparsed;
  143. http_parser_pause(parser, 1);
  144. parser_data->paused = true;
  145. ESP_LOGD(TAG, LOG_FMT("paused"));
  146. return ESP_OK;
  147. }
  148. static size_t continue_parsing(http_parser *parser, size_t length)
  149. {
  150. parser_data_t *data = (parser_data_t *) parser->data;
  151. /* Part of the received data may have been parsed earlier
  152. * so we must skip that before parsing resumes */
  153. length = MIN(length, data->pre_parsed);
  154. data->pre_parsed -= length;
  155. ESP_LOGD(TAG, LOG_FMT("skip pre-parsed data of size = %d"), length);
  156. http_parser_pause(parser, 0);
  157. data->paused = false;
  158. ESP_LOGD(TAG, LOG_FMT("un-paused"));
  159. return length;
  160. }
  161. /* http_parser callback on header field in HTTP request
  162. * May be invoked ATLEAST once every header field
  163. */
  164. static esp_err_t cb_header_field(http_parser *parser, const char *at, size_t length)
  165. {
  166. parser_data_t *parser_data = (parser_data_t *) parser->data;
  167. struct httpd_req *r = parser_data->req;
  168. struct httpd_req_aux *ra = r->aux;
  169. /* Check previous status */
  170. if (parser_data->status == PARSING_URL) {
  171. if (verify_url(parser) != ESP_OK) {
  172. /* verify_url would already have set the
  173. * error field of parser data, so only setting
  174. * status to failed */
  175. parser_data->status = PARSING_FAILED;
  176. return ESP_FAIL;
  177. }
  178. ESP_LOGD(TAG, LOG_FMT("headers begin"));
  179. /* Last at is set to start of scratch where headers
  180. * will be received next */
  181. parser_data->last.at = ra->scratch;
  182. parser_data->last.length = 0;
  183. parser_data->status = PARSING_HDR_FIELD;
  184. /* Stop parsing for now and give control to process */
  185. if (pause_parsing(parser, at) != ESP_OK) {
  186. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  187. parser_data->status = PARSING_FAILED;
  188. return ESP_FAIL;
  189. }
  190. } else if (parser_data->status == PARSING_HDR_VALUE) {
  191. /* Overwrite terminator (CRLFs) following last header
  192. * (key: value) pair with null characters */
  193. char *term_start = (char *)parser_data->last.at + parser_data->last.length;
  194. memset(term_start, '\0', at - term_start);
  195. /* Store current values of the parser callback arguments */
  196. parser_data->last.at = at;
  197. parser_data->last.length = 0;
  198. parser_data->status = PARSING_HDR_FIELD;
  199. /* Increment header count */
  200. ra->req_hdrs_count++;
  201. } else if (parser_data->status != PARSING_HDR_FIELD) {
  202. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  203. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  204. parser_data->status = PARSING_FAILED;
  205. return ESP_FAIL;
  206. }
  207. ESP_LOGD(TAG, LOG_FMT("processing field = %.*s"), length, at);
  208. /* Update length of header string */
  209. parser_data->last.length += length;
  210. return ESP_OK;
  211. }
  212. /* http_parser callback on header value in HTTP request.
  213. * May be invoked ATLEAST once every header value
  214. */
  215. static esp_err_t cb_header_value(http_parser *parser, const char *at, size_t length)
  216. {
  217. parser_data_t *parser_data = (parser_data_t *) parser->data;
  218. /* Check previous status */
  219. if (parser_data->status == PARSING_HDR_FIELD) {
  220. /* Store current values of the parser callback arguments */
  221. parser_data->last.at = at;
  222. parser_data->last.length = 0;
  223. parser_data->status = PARSING_HDR_VALUE;
  224. if (length == 0) {
  225. /* As per behavior of http_parser, when length > 0,
  226. * `at` points to the start of CRLF. But, in the
  227. * case when header value is empty (zero length),
  228. * then `at` points to the position right after
  229. * the CRLF. Since for our purpose we need `last.at`
  230. * to point to exactly where the CRLF starts, it
  231. * needs to be adjusted by the right offset */
  232. char *at_adj = (char *)parser_data->last.at;
  233. /* Find the end of header field string */
  234. while (*(--at_adj) != ':');
  235. /* Now skip leading spaces' */
  236. while (*(++at_adj) == ' ');
  237. /* Now we are at the right position */
  238. parser_data->last.at = at_adj;
  239. }
  240. } else if (parser_data->status != PARSING_HDR_VALUE) {
  241. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  242. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  243. parser_data->status = PARSING_FAILED;
  244. return ESP_FAIL;
  245. }
  246. ESP_LOGD(TAG, LOG_FMT("processing value = %.*s"), length, at);
  247. /* Update length of header string */
  248. parser_data->last.length += length;
  249. return ESP_OK;
  250. }
  251. /* http_parser callback on completing headers in HTTP request.
  252. * Will be invoked ONLY once every packet
  253. */
  254. static esp_err_t cb_headers_complete(http_parser *parser)
  255. {
  256. parser_data_t *parser_data = (parser_data_t *) parser->data;
  257. struct httpd_req *r = parser_data->req;
  258. struct httpd_req_aux *ra = r->aux;
  259. /* Check previous status */
  260. if (parser_data->status == PARSING_URL) {
  261. ESP_LOGD(TAG, LOG_FMT("no headers"));
  262. if (verify_url(parser) != ESP_OK) {
  263. /* verify_url would already have set the
  264. * error field of parser data, so only setting
  265. * status to failed */
  266. parser_data->status = PARSING_FAILED;
  267. return ESP_FAIL;
  268. }
  269. } else if (parser_data->status == PARSING_HDR_VALUE) {
  270. /* Locate end of last header */
  271. char *at = (char *)parser_data->last.at + parser_data->last.length;
  272. /* Check if there is data left to parse. This value should
  273. * at least be equal to the number of line terminators, i.e. 2 */
  274. ssize_t remaining_length = parser_data->raw_datalen - (at - ra->scratch);
  275. if (remaining_length < 2) {
  276. ESP_LOGE(TAG, LOG_FMT("invalid length of data remaining to be parsed"));
  277. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  278. parser_data->status = PARSING_FAILED;
  279. return ESP_FAIL;
  280. }
  281. /* Locate end of headers section by skipping the remaining
  282. * two line terminators. No assumption is made here about the
  283. * termination sequence used apart from the necessity that it
  284. * must end with an LF, because:
  285. * 1) some clients may send non standard LFs instead of
  286. * CRLFs for indicating termination.
  287. * 2) it is the responsibility of http_parser to check
  288. * that the termination is either CRLF or LF and
  289. * not any other sequence */
  290. unsigned short remaining_terminators = 2;
  291. while (remaining_length-- && remaining_terminators) {
  292. if (*at == '\n') {
  293. remaining_terminators--;
  294. }
  295. /* Overwrite termination characters with null */
  296. *(at++) = '\0';
  297. }
  298. if (remaining_terminators) {
  299. ESP_LOGE(TAG, LOG_FMT("incomplete termination of headers"));
  300. parser_data->error = HTTPD_400_BAD_REQUEST;
  301. parser_data->status = PARSING_FAILED;
  302. return ESP_FAIL;
  303. }
  304. /* Place the parser ptr right after the end of headers section */
  305. parser_data->last.at = at;
  306. /* Increment header count */
  307. ra->req_hdrs_count++;
  308. } else {
  309. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  310. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  311. parser_data->status = PARSING_FAILED;
  312. return ESP_FAIL;
  313. }
  314. /* In absence of body/chunked encoding, http_parser sets content_len to -1 */
  315. r->content_len = ((int)parser->content_length != -1 ?
  316. parser->content_length : 0);
  317. ESP_LOGD(TAG, LOG_FMT("bytes read = %d"), parser->nread);
  318. ESP_LOGD(TAG, LOG_FMT("content length = %zu"), r->content_len);
  319. /* Handle upgrade requests - only WebSocket is supported for now */
  320. if (parser->upgrade) {
  321. #ifdef CONFIG_HTTPD_WS_SUPPORT
  322. ESP_LOGD(TAG, LOG_FMT("Got an upgrade request"));
  323. /* If there's no "Upgrade" header field, then it's not WebSocket. */
  324. char ws_upgrade_hdr_val[] = "websocket";
  325. if (httpd_req_get_hdr_value_str(r, "Upgrade", ws_upgrade_hdr_val, sizeof(ws_upgrade_hdr_val)) != ESP_OK) {
  326. ESP_LOGW(TAG, LOG_FMT("Upgrade header does not match the length of \"websocket\""));
  327. parser_data->error = HTTPD_400_BAD_REQUEST;
  328. parser_data->status = PARSING_FAILED;
  329. return ESP_FAIL;
  330. }
  331. /* If "Upgrade" field's key is not "websocket", then we should also forget about it. */
  332. if (strcasecmp("websocket", ws_upgrade_hdr_val) != 0) {
  333. ESP_LOGW(TAG, LOG_FMT("Upgrade header found but it's %s"), ws_upgrade_hdr_val);
  334. parser_data->error = HTTPD_400_BAD_REQUEST;
  335. parser_data->status = PARSING_FAILED;
  336. return ESP_FAIL;
  337. }
  338. /* Now set handshake flag to true */
  339. ra->ws_handshake_detect = true;
  340. #else
  341. ESP_LOGD(TAG, LOG_FMT("WS functions has been disabled, Upgrade request is not supported."));
  342. parser_data->error = HTTPD_400_BAD_REQUEST;
  343. parser_data->status = PARSING_FAILED;
  344. return ESP_FAIL;
  345. #endif
  346. }
  347. parser_data->status = PARSING_BODY;
  348. ra->remaining_len = r->content_len;
  349. return ESP_OK;
  350. }
  351. /* Last http_parser callback if body present in HTTP request.
  352. * Will be invoked ONLY once every packet
  353. */
  354. static esp_err_t cb_on_body(http_parser *parser, const char *at, size_t length)
  355. {
  356. parser_data_t *parser_data = (parser_data_t *) parser->data;
  357. /* Check previous status */
  358. if (parser_data->status != PARSING_BODY) {
  359. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  360. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  361. parser_data->status = PARSING_FAILED;
  362. return ESP_FAIL;
  363. }
  364. /* Pause parsing so that if part of another packet
  365. * is in queue then it doesn't get parsed, which
  366. * may reset the parser state and cause current
  367. * request packet to be lost */
  368. if (pause_parsing(parser, at) != ESP_OK) {
  369. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  370. parser_data->status = PARSING_FAILED;
  371. return ESP_FAIL;
  372. }
  373. parser_data->last.at = 0;
  374. parser_data->last.length = 0;
  375. parser_data->status = PARSING_COMPLETE;
  376. ESP_LOGD(TAG, LOG_FMT("body begins"));
  377. return ESP_OK;
  378. }
  379. /* Last http_parser callback if body absent in HTTP request.
  380. * Will be invoked ONLY once every packet
  381. */
  382. static esp_err_t cb_no_body(http_parser *parser)
  383. {
  384. parser_data_t *parser_data = (parser_data_t *) parser->data;
  385. /* Check previous status */
  386. if (parser_data->status == PARSING_URL) {
  387. ESP_LOGD(TAG, LOG_FMT("no headers"));
  388. if (verify_url(parser) != ESP_OK) {
  389. /* verify_url would already have set the
  390. * error field of parser data, so only setting
  391. * status to failed */
  392. parser_data->status = PARSING_FAILED;
  393. return ESP_FAIL;
  394. }
  395. } else if (parser_data->status != PARSING_BODY) {
  396. ESP_LOGE(TAG, LOG_FMT("unexpected state transition"));
  397. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  398. parser_data->status = PARSING_FAILED;
  399. return ESP_FAIL;
  400. }
  401. /* Pause parsing so that if part of another packet
  402. * is in queue then it doesn't get parsed, which
  403. * may reset the parser state and cause current
  404. * request packet to be lost */
  405. if (pause_parsing(parser, parser_data->last.at) != ESP_OK) {
  406. parser_data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  407. parser_data->status = PARSING_FAILED;
  408. return ESP_FAIL;
  409. }
  410. parser_data->last.at = 0;
  411. parser_data->last.length = 0;
  412. parser_data->status = PARSING_COMPLETE;
  413. ESP_LOGD(TAG, LOG_FMT("message complete"));
  414. return ESP_OK;
  415. }
  416. static int read_block(httpd_req_t *req, size_t offset, size_t length)
  417. {
  418. struct httpd_req_aux *raux = req->aux;
  419. /* Limits the read to scratch buffer size */
  420. ssize_t buf_len = MIN(length, (sizeof(raux->scratch) - offset));
  421. if (buf_len <= 0) {
  422. return 0;
  423. }
  424. /* Receive data into buffer. If data is pending (from unrecv) then return
  425. * immediately after receiving pending data, as pending data may just complete
  426. * this request packet. */
  427. int nbytes = httpd_recv_with_opt(req, raux->scratch + offset, buf_len, true);
  428. if (nbytes < 0) {
  429. ESP_LOGD(TAG, LOG_FMT("error in httpd_recv"));
  430. /* If timeout occurred allow the
  431. * situation to be handled */
  432. if (nbytes == HTTPD_SOCK_ERR_TIMEOUT) {
  433. /* Invoke error handler which may return ESP_OK
  434. * to signal for retrying call to recv(), else it may
  435. * return ESP_FAIL to signal for closure of socket */
  436. return (httpd_req_handle_err(req, HTTPD_408_REQ_TIMEOUT) == ESP_OK) ?
  437. HTTPD_SOCK_ERR_TIMEOUT : HTTPD_SOCK_ERR_FAIL;
  438. }
  439. /* Some socket error occurred. Return failure
  440. * to force closure of underlying socket.
  441. * Error message is not sent as socket may not
  442. * be valid anymore */
  443. return HTTPD_SOCK_ERR_FAIL;
  444. } else if (nbytes == 0) {
  445. ESP_LOGD(TAG, LOG_FMT("connection closed"));
  446. /* Connection closed by client so no
  447. * need to send error response */
  448. return HTTPD_SOCK_ERR_FAIL;
  449. }
  450. ESP_LOGD(TAG, LOG_FMT("received HTTP request block size = %d"), nbytes);
  451. return nbytes;
  452. }
  453. static int parse_block(http_parser *parser, size_t offset, size_t length)
  454. {
  455. parser_data_t *data = (parser_data_t *)(parser->data);
  456. httpd_req_t *req = data->req;
  457. struct httpd_req_aux *raux = req->aux;
  458. size_t nparsed = 0;
  459. if (!length) {
  460. /* Parsing is still happening but nothing to
  461. * parse means no more space left on buffer,
  462. * therefore it can be inferred that the
  463. * request URI/header must be too long */
  464. ESP_LOGW(TAG, LOG_FMT("request URI/header too long"));
  465. switch (data->status) {
  466. case PARSING_URL:
  467. data->error = HTTPD_414_URI_TOO_LONG;
  468. break;
  469. case PARSING_HDR_FIELD:
  470. case PARSING_HDR_VALUE:
  471. data->error = HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE;
  472. break;
  473. default:
  474. ESP_LOGE(TAG, LOG_FMT("unexpected state"));
  475. data->error = HTTPD_500_INTERNAL_SERVER_ERROR;
  476. break;
  477. }
  478. data->status = PARSING_FAILED;
  479. return -1;
  480. }
  481. /* Un-pause the parsing if paused */
  482. if (data->paused) {
  483. nparsed = continue_parsing(parser, length);
  484. length -= nparsed;
  485. offset += nparsed;
  486. if (!length) {
  487. return nparsed;
  488. }
  489. }
  490. /* Execute http_parser */
  491. nparsed = http_parser_execute(parser, &data->settings,
  492. raux->scratch + offset, length);
  493. /* Check state */
  494. if (data->status == PARSING_FAILED) {
  495. /* It is expected that the error field of
  496. * parser data should have been set by now */
  497. ESP_LOGW(TAG, LOG_FMT("parsing failed"));
  498. return -1;
  499. } else if (data->paused) {
  500. /* Update the value of pre_parsed which was set when
  501. * pause_parsing() was called. (length - nparsed) is
  502. * the length of the data that will need to be parsed
  503. * again later and hence must be deducted from the
  504. * pre_parsed length */
  505. data->pre_parsed -= (length - nparsed);
  506. return 0;
  507. } else if (nparsed != length) {
  508. /* http_parser error */
  509. data->error = HTTPD_400_BAD_REQUEST;
  510. data->status = PARSING_FAILED;
  511. ESP_LOGW(TAG, LOG_FMT("incomplete (%d/%d) with parser error = %d"),
  512. nparsed, length, parser->http_errno);
  513. return -1;
  514. }
  515. /* Return with the total length of the request packet
  516. * that has been parsed till now */
  517. ESP_LOGD(TAG, LOG_FMT("parsed block size = %d"), offset + nparsed);
  518. return offset + nparsed;
  519. }
  520. static void parse_init(httpd_req_t *r, http_parser *parser, parser_data_t *data)
  521. {
  522. /* Initialize parser data */
  523. memset(data, 0, sizeof(parser_data_t));
  524. data->req = r;
  525. /* Initialize parser */
  526. http_parser_init(parser, HTTP_REQUEST);
  527. parser->data = (void *)data;
  528. /* Initialize parser settings */
  529. http_parser_settings_init(&data->settings);
  530. /* Set parser callbacks */
  531. data->settings.on_url = cb_url;
  532. data->settings.on_header_field = cb_header_field;
  533. data->settings.on_header_value = cb_header_value;
  534. data->settings.on_headers_complete = cb_headers_complete;
  535. data->settings.on_body = cb_on_body;
  536. data->settings.on_message_complete = cb_no_body;
  537. }
  538. /* Function that receives TCP data and runs parser on it
  539. */
  540. static esp_err_t httpd_parse_req(struct httpd_data *hd)
  541. {
  542. httpd_req_t *r = &hd->hd_req;
  543. int blk_len, offset;
  544. http_parser parser = {};
  545. parser_data_t parser_data = {};
  546. /* Initialize parser */
  547. parse_init(r, &parser, &parser_data);
  548. /* Set offset to start of scratch buffer */
  549. offset = 0;
  550. do {
  551. /* Read block into scratch buffer */
  552. if ((blk_len = read_block(r, offset, PARSER_BLOCK_SIZE)) < 0) {
  553. if (blk_len == HTTPD_SOCK_ERR_TIMEOUT) {
  554. /* Retry read in case of non-fatal timeout error.
  555. * read_block() ensures that the timeout error is
  556. * handled properly so that this doesn't get stuck
  557. * in an infinite loop */
  558. continue;
  559. }
  560. /* If not HTTPD_SOCK_ERR_TIMEOUT, returned error must
  561. * be HTTPD_SOCK_ERR_FAIL which means we need to return
  562. * failure and thereby close the underlying socket */
  563. return ESP_FAIL;
  564. }
  565. /* This is used by the callbacks to track
  566. * data usage of the buffer */
  567. parser_data.raw_datalen = blk_len + offset;
  568. /* Parse data block from buffer */
  569. if ((offset = parse_block(&parser, offset, blk_len)) < 0) {
  570. /* HTTP error occurred.
  571. * Send error code as response status and
  572. * invoke error handler */
  573. return httpd_req_handle_err(r, parser_data.error);
  574. }
  575. } while (parser_data.status != PARSING_COMPLETE);
  576. ESP_LOGD(TAG, LOG_FMT("parsing complete"));
  577. return httpd_uri(hd);
  578. }
  579. static void init_req(httpd_req_t *r, httpd_config_t *config)
  580. {
  581. r->handle = 0;
  582. r->method = 0;
  583. memset((char*)r->uri, 0, sizeof(r->uri));
  584. r->content_len = 0;
  585. r->aux = 0;
  586. r->user_ctx = 0;
  587. r->sess_ctx = 0;
  588. r->free_ctx = 0;
  589. r->ignore_sess_ctx_changes = 0;
  590. }
  591. static void init_req_aux(struct httpd_req_aux *ra, httpd_config_t *config)
  592. {
  593. ra->sd = 0;
  594. memset(ra->scratch, 0, sizeof(ra->scratch));
  595. ra->remaining_len = 0;
  596. ra->status = 0;
  597. ra->content_type = 0;
  598. ra->first_chunk_sent = 0;
  599. ra->req_hdrs_count = 0;
  600. ra->resp_hdrs_count = 0;
  601. #if CONFIG_HTTPD_WS_SUPPORT
  602. ra->ws_handshake_detect = false;
  603. #endif
  604. memset(ra->resp_hdrs, 0, config->max_resp_headers * sizeof(struct resp_hdr));
  605. }
  606. static void httpd_req_cleanup(httpd_req_t *r)
  607. {
  608. struct httpd_req_aux *ra = r->aux;
  609. /* Check if the context has changed and needs to be cleared */
  610. if ((r->ignore_sess_ctx_changes == false) && (ra->sd->ctx != r->sess_ctx)) {
  611. httpd_sess_free_ctx(ra->sd->ctx, ra->sd->free_ctx);
  612. }
  613. #if CONFIG_HTTPD_WS_SUPPORT
  614. /* Close the socket when a WebSocket Close request is received */
  615. if (ra->sd->ws_close) {
  616. ESP_LOGD(TAG, LOG_FMT("Try closing WS connection at FD: %d"), ra->sd->fd);
  617. httpd_sess_trigger_close(r->handle, ra->sd->fd);
  618. }
  619. #endif
  620. /* Retrieve session info from the request into the socket database. */
  621. ra->sd->ctx = r->sess_ctx;
  622. ra->sd->free_ctx = r->free_ctx;
  623. ra->sd->ignore_sess_ctx_changes = r->ignore_sess_ctx_changes;
  624. /* Clear out the request and request_aux structures */
  625. ra->sd = NULL;
  626. r->handle = NULL;
  627. r->aux = NULL;
  628. r->user_ctx = NULL;
  629. }
  630. /* Function that processes incoming TCP data and
  631. * updates the http request data httpd_req_t
  632. */
  633. esp_err_t httpd_req_new(struct httpd_data *hd, struct sock_db *sd)
  634. {
  635. httpd_req_t *r = &hd->hd_req;
  636. init_req(r, &hd->config);
  637. init_req_aux(&hd->hd_req_aux, &hd->config);
  638. r->handle = hd;
  639. r->aux = &hd->hd_req_aux;
  640. /* Associate the request to the socket */
  641. struct httpd_req_aux *ra = r->aux;
  642. ra->sd = sd;
  643. /* Set defaults */
  644. ra->status = (char *)HTTPD_200;
  645. ra->content_type = (char *)HTTPD_TYPE_TEXT;
  646. ra->first_chunk_sent = false;
  647. /* Copy session info to the request */
  648. r->sess_ctx = sd->ctx;
  649. r->free_ctx = sd->free_ctx;
  650. r->ignore_sess_ctx_changes = sd->ignore_sess_ctx_changes;
  651. esp_err_t ret;
  652. #ifdef CONFIG_HTTPD_WS_SUPPORT
  653. /* Copy user_ctx to the request */
  654. r->user_ctx = sd->ws_user_ctx;
  655. /* Handle WebSocket */
  656. ESP_LOGD(TAG, LOG_FMT("New request, has WS? %s, sd->ws_handler valid? %s, sd->ws_close? %s"),
  657. sd->ws_handshake_done ? "Yes" : "No",
  658. sd->ws_handler != NULL ? "Yes" : "No",
  659. sd->ws_close ? "Yes" : "No");
  660. if (sd->ws_handshake_done && sd->ws_handler != NULL) {
  661. if (sd->ws_close == true) {
  662. /* WS was marked as close state, do not deal with this socket */
  663. ESP_LOGD(TAG, LOG_FMT("WS was marked close"));
  664. return ESP_OK;
  665. }
  666. ret = httpd_ws_get_frame_type(r);
  667. ESP_LOGD(TAG, LOG_FMT("New WS request from existing socket, ws_type=%d"), ra->ws_type);
  668. if (ra->ws_type == HTTPD_WS_TYPE_CLOSE) {
  669. /* Only mark ws_close to true if it's a CLOSE frame */
  670. sd->ws_close = true;
  671. } else if (ra->ws_type == HTTPD_WS_TYPE_PONG) {
  672. /* Pass the PONG frames to the handler as well, as user app might send PINGs */
  673. ESP_LOGD(TAG, LOG_FMT("Received PONG frame"));
  674. }
  675. /* Call handler if it's a non-control frame (or if handler requests control frames, as well) */
  676. if (ret == ESP_OK &&
  677. (ra->ws_type < HTTPD_WS_TYPE_CLOSE || sd->ws_control_frames)) {
  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. }
  933. /* Helper function to get a cookie value from a cookie string of the type "cookie1=val1; cookie2=val2" */
  934. esp_err_t static httpd_cookie_key_value(const char *cookie_str, const char *key, char *val, size_t *val_size)
  935. {
  936. if (cookie_str == NULL || key == NULL || val == NULL) {
  937. return ESP_ERR_INVALID_ARG;
  938. }
  939. const char *cookie_ptr = cookie_str;
  940. const size_t buf_len = *val_size;
  941. size_t _val_size = *val_size;
  942. while (strlen(cookie_ptr)) {
  943. /* Search for the '=' character. Else, it would mean
  944. * that the parameter is invalid */
  945. const char *val_ptr = strchr(cookie_ptr, '=');
  946. if (!val_ptr) {
  947. break;
  948. }
  949. size_t offset = val_ptr - cookie_ptr;
  950. /* If the key, does not match, continue searching.
  951. * Compare lengths first as key from cookie string is not
  952. * null terminated (has '=' in the end) */
  953. if ((offset != strlen(key)) || (strncasecmp(cookie_ptr, key, offset) != 0)) {
  954. /* Get the name=val string. Multiple name=value pairs
  955. * are separated by '; ' */
  956. cookie_ptr = strchr(val_ptr, ' ');
  957. if (!cookie_ptr) {
  958. break;
  959. }
  960. cookie_ptr++;
  961. continue;
  962. }
  963. /* Locate start of next query */
  964. cookie_ptr = strchr(++val_ptr, ';');
  965. /* Or this could be the last query, in which
  966. * case get to the end of query string */
  967. if (!cookie_ptr) {
  968. cookie_ptr = val_ptr + strlen(val_ptr);
  969. }
  970. /* Update value length, including one byte for null */
  971. _val_size = cookie_ptr - val_ptr + 1;
  972. /* Copy value to the caller's buffer. */
  973. strlcpy(val, val_ptr, MIN(_val_size, buf_len));
  974. /* If buffer length is smaller than needed, return truncation error */
  975. if (buf_len < _val_size) {
  976. *val_size = _val_size;
  977. return ESP_ERR_HTTPD_RESULT_TRUNC;
  978. }
  979. /* Save amount of bytes copied to caller's buffer */
  980. *val_size = MIN(_val_size, buf_len);
  981. return ESP_OK;
  982. }
  983. ESP_LOGD(TAG, LOG_FMT("cookie %s not found"), key);
  984. return ESP_ERR_NOT_FOUND;
  985. }
  986. /* Get the value of a cookie from the request headers */
  987. esp_err_t httpd_req_get_cookie_val(httpd_req_t *req, const char *cookie_name, char *val, size_t *val_size)
  988. {
  989. esp_err_t ret;
  990. size_t hdr_len_cookie = httpd_req_get_hdr_value_len(req, "Cookie");
  991. char *cookie_str = NULL;
  992. if (hdr_len_cookie <= 0) {
  993. return ESP_ERR_NOT_FOUND;
  994. }
  995. cookie_str = malloc(hdr_len_cookie + 1);
  996. if (cookie_str == NULL) {
  997. ESP_LOGE(TAG, "Failed to allocate memory for cookie string");
  998. return ESP_ERR_NO_MEM;
  999. }
  1000. if (httpd_req_get_hdr_value_str(req, "Cookie", cookie_str, hdr_len_cookie + 1) != ESP_OK) {
  1001. ESP_LOGW(TAG, "Cookie not found in header uri:[%s]", req->uri);
  1002. free(cookie_str);
  1003. return ESP_ERR_NOT_FOUND;
  1004. }
  1005. ret = httpd_cookie_key_value(cookie_str, cookie_name, val, val_size);
  1006. free(cookie_str);
  1007. return ret;
  1008. }