httpd_parse.c 40 KB

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