httpd_parse.c 33 KB

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