httpd_parse.c 39 KB

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