http_server.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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. #ifndef _HTTP_SERVER_H_
  15. #define _HTTP_SERVER_H_
  16. #include <stdio.h>
  17. #include <string.h>
  18. #include <freertos/FreeRTOS.h>
  19. #include <freertos/task.h>
  20. #include <http_parser.h>
  21. #include <sdkconfig.h>
  22. #include <esp_err.h>
  23. #ifdef __cplusplus
  24. extern "C" {
  25. #endif
  26. #define HTTPD_DEFAULT_CONFIG() { \
  27. .task_priority = tskIDLE_PRIORITY+5, \
  28. .stack_size = 4096, \
  29. .server_port = 80, \
  30. .ctrl_port = 32768, \
  31. .max_open_sockets = 7, \
  32. .max_uri_handlers = 8, \
  33. .max_resp_headers = 8, \
  34. .backlog_conn = 5, \
  35. .lru_purge_enable = false, \
  36. .recv_wait_timeout = 5, \
  37. .send_wait_timeout = 5, \
  38. };
  39. #define ESP_ERR_HTTPD_BASE (0x8000) /*!< Starting number of HTTPD error codes */
  40. #define ESP_ERR_HTTPD_HANDLERS_FULL (ESP_ERR_HTTPD_BASE + 1) /*!< All slots for registering URI handlers have been consumed */
  41. #define ESP_ERR_HTTPD_HANDLER_EXISTS (ESP_ERR_HTTPD_BASE + 2) /*!< URI handler with same method and target URI already registered */
  42. #define ESP_ERR_HTTPD_INVALID_REQ (ESP_ERR_HTTPD_BASE + 3) /*!< Invalid request pointer */
  43. #define ESP_ERR_HTTPD_RESULT_TRUNC (ESP_ERR_HTTPD_BASE + 4) /*!< Result string truncated */
  44. #define ESP_ERR_HTTPD_RESP_HDR (ESP_ERR_HTTPD_BASE + 5) /*!< Response header field larger than supported */
  45. #define ESP_ERR_HTTPD_RESP_SEND (ESP_ERR_HTTPD_BASE + 6) /*!< Error occured while sending response packet */
  46. #define ESP_ERR_HTTPD_ALLOC_MEM (ESP_ERR_HTTPD_BASE + 7) /*!< Failed to dynamically allocate memory for resource */
  47. #define ESP_ERR_HTTPD_TASK (ESP_ERR_HTTPD_BASE + 8) /*!< Failed to launch server task/thread */
  48. /* ************** Group: Initialization ************** */
  49. /** @name Initialization
  50. * APIs related to the Initialization of the web server
  51. * @{
  52. */
  53. /**
  54. * @brief HTTP Server Instance Handle
  55. *
  56. * Every instance of the server will have a unique handle.
  57. */
  58. typedef void* httpd_handle_t;
  59. /**
  60. * @brief HTTP Method Type wrapper over "enum http_method"
  61. * available in "http_parser" library
  62. */
  63. typedef enum http_method httpd_method_t;
  64. /**
  65. * @brief HTTP Server Configuration Structure
  66. *
  67. * @note Use HTTPD_DEFAULT_CONFIG() to initialize the configuration
  68. * to a default value and then modify only those fields that are
  69. * specifically determined by the use case.
  70. */
  71. typedef struct httpd_config {
  72. unsigned task_priority; /*!< Priority of FreeRTOS task which runs the server */
  73. size_t stack_size; /*!< The maximum stack size allowed for the server task */
  74. /**
  75. * TCP Port number for receiving and transmitting HTTP traffic
  76. */
  77. uint16_t server_port;
  78. /**
  79. * UDP Port number for asynchronously exchanging control signals
  80. * between various components of the server
  81. */
  82. uint16_t ctrl_port;
  83. uint16_t max_open_sockets; /*!< Max number of sockets/clients connected at any time*/
  84. uint16_t max_uri_handlers; /*!< Maximum allowed uri handlers */
  85. uint16_t max_resp_headers; /*!< Maximum allowed additional headers in HTTP response */
  86. uint16_t backlog_conn; /*!< Number of backlog connections */
  87. bool lru_purge_enable; /*!< Purge "Least Recently Used" connection */
  88. uint16_t recv_wait_timeout; /*!< Timeout for recv function (in seconds)*/
  89. uint16_t send_wait_timeout; /*!< Timeout for send function (in seconds)*/
  90. } httpd_config_t;
  91. /**
  92. * @brief Starts the web server
  93. *
  94. * Create an instance of HTTP server and allocate memory/resources for it
  95. * depending upon the specified configuration.
  96. *
  97. * Example usage:
  98. * @code{c}
  99. *
  100. * //Function for starting the webserver
  101. * httpd_handle_t start_webserver(void)
  102. * {
  103. * // Generate default configuration
  104. * httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  105. *
  106. * // Empty handle to http_server
  107. * httpd_handle_t server = NULL;
  108. *
  109. * // Start the httpd server
  110. * if (httpd_start(&server, &config) == ESP_OK) {
  111. * // Register URI handlers
  112. * httpd_register_uri_handler(server, &uri_get);
  113. * httpd_register_uri_handler(server, &uri_post);
  114. * }
  115. * // If server failed to start, handle will be NULL
  116. * return server;
  117. * }
  118. *
  119. * @endcode
  120. *
  121. * @param[in] config : Configuration for new instance of the server
  122. * @param[out] handle : Handle to newly created instance of the server. NULL on error
  123. * @return
  124. * - ESP_OK : Instance created successfully
  125. * - ESP_ERR_INVALID_ARG : Null argument(s)
  126. * - ESP_ERR_HTTPD_ALLOC_MEM : Failed to allocate memory for instance
  127. * - ESP_ERR_HTTPD_TASK : Failed to launch server task
  128. */
  129. esp_err_t httpd_start(httpd_handle_t *handle, const httpd_config_t *config);
  130. /**
  131. * @brief Stops the web server
  132. *
  133. * Deallocates memory/resources used by an HTTP server instance and
  134. * deletes it. Once deleted the handle can no longer be used for accessing
  135. * the instance.
  136. *
  137. * Example usage:
  138. * @code{c}
  139. *
  140. * // Function for stopping the webserver
  141. * void stop_webserver(httpd_handle_t server)
  142. * {
  143. * // Ensure handle is non NULL
  144. * if (server != NULL) {
  145. * // Stop the httpd server
  146. * httpd_stop(server);
  147. * }
  148. * }
  149. *
  150. * @endcode
  151. *
  152. * @param[in] handle Handle to server returned by httpd_start
  153. * @return
  154. * - ESP_OK : Server stopped successfully
  155. * - ESP_ERR_INVALID_ARG : Handle argument is Null
  156. */
  157. esp_err_t httpd_stop(httpd_handle_t handle);
  158. /** End of Group Initialization
  159. * @}
  160. */
  161. /* ************** Group: URI Handlers ************** */
  162. /** @name URI Handlers
  163. * APIs related to the URI handlers
  164. * @{
  165. */
  166. /**
  167. * @brief Function type for freeing context data (if any)
  168. */
  169. typedef void (*httpd_free_sess_ctx_fn_t)(void *sess_ctx);
  170. /* Max supported HTTP request header length */
  171. #define HTTPD_MAX_REQ_HDR_LEN CONFIG_HTTPD_MAX_REQ_HDR_LEN
  172. /* Max supported HTTP request URI length */
  173. #define HTTPD_MAX_URI_LEN CONFIG_HTTPD_MAX_URI_LEN
  174. /**
  175. * @brief HTTP Request Data Structure
  176. */
  177. typedef struct httpd_req {
  178. httpd_handle_t handle; /*!< Handle to server instance */
  179. int method; /*!< The type of HTTP request, -1 if unsupported method */
  180. const char uri[HTTPD_MAX_URI_LEN + 1]; /*!< The URI of this request (1 byte extra for null termination) */
  181. size_t content_len; /*!< Length of the request body */
  182. void *aux; /*!< Internally used members */
  183. /**
  184. * User context pointer passed during URI registration.
  185. */
  186. void *user_ctx;
  187. /**
  188. * Session Context Pointer
  189. *
  190. * A session context. Contexts are maintained across 'sessions' for a
  191. * given open TCP connection. One session could have multiple request
  192. * responses. The web server will ensure that the context persists
  193. * across all these request and responses.
  194. *
  195. * By default, this is NULL. URI Handlers can set this to any meaningful
  196. * value.
  197. *
  198. * If the underlying socket gets closed, and this pointer is non-NULL,
  199. * the web server will free up the context by calling free(), unless
  200. * free_ctx function is set.
  201. */
  202. void *sess_ctx;
  203. /**
  204. * Pointer to free context hook
  205. *
  206. * Function to free session context
  207. *
  208. * If the web server's socket closes, it frees up the session context by
  209. * calling free() on the sess_ctx member. If you wish to use a custom
  210. * function for freeing the session context, please specify that here.
  211. */
  212. httpd_free_sess_ctx_fn_t free_ctx;
  213. } httpd_req_t;
  214. /**
  215. * @brief Structure for URI handler
  216. */
  217. typedef struct httpd_uri {
  218. const char *uri; /*!< The URI to handle */
  219. httpd_method_t method; /*!< Method supported by the URI */
  220. /**
  221. * Handler to call for supported request method. This must
  222. * return ESP_OK, or else the underlying socket will be closed.
  223. */
  224. esp_err_t (*handler)(httpd_req_t *r);
  225. /**
  226. * Pointer to user context data which will be available to handler
  227. */
  228. void *user_ctx;
  229. } httpd_uri_t;
  230. /**
  231. * @brief Registers a URI handler
  232. *
  233. * @note URI handlers can be registered in real time as long as the
  234. * server handle is valid.
  235. *
  236. * Example usage:
  237. * @code{c}
  238. *
  239. * esp_err_t my_uri_handler(httpd_req_t* req)
  240. * {
  241. * // Recv , Process and Send
  242. * ....
  243. * ....
  244. * ....
  245. *
  246. * // Fail condition
  247. * if (....) {
  248. * // Return fail to close session //
  249. * return ESP_FAIL;
  250. * }
  251. *
  252. * // On success
  253. * return ESP_OK;
  254. * }
  255. *
  256. * // URI handler structure
  257. * httpd_uri_t my_uri {
  258. * .uri = "/my_uri/path/xyz",
  259. * .method = HTTPD_GET,
  260. * .handler = my_uri_handler,
  261. * .user_ctx = NULL
  262. * };
  263. *
  264. * // Register handler
  265. * if (httpd_register_uri_handler(server_handle, &my_uri) != ESP_OK) {
  266. * // If failed to register handler
  267. * ....
  268. * }
  269. *
  270. * @endcode
  271. *
  272. * @param[in] handle handle to HTTPD server instance
  273. * @param[in] uri_handler pointer to handler that needs to be registered
  274. *
  275. * @return
  276. * - ESP_OK : On successfully registering the handler
  277. * - ESP_ERR_INVALID_ARG : Null arguments
  278. * - ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler
  279. * - ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and
  280. * method is already registered
  281. */
  282. esp_err_t httpd_register_uri_handler(httpd_handle_t handle,
  283. const httpd_uri_t *uri_handler);
  284. /**
  285. * @brief Unregister a URI handler
  286. *
  287. * @param[in] handle handle to HTTPD server instance
  288. * @param[in] uri URI string
  289. * @param[in] method HTTP method
  290. *
  291. * @return
  292. * - ESP_OK : On successfully deregistering the handler
  293. * - ESP_ERR_INVALID_ARG : Null arguments
  294. * - ESP_ERR_NOT_FOUND : Handler with specified URI and method not found
  295. */
  296. esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle,
  297. const char *uri, httpd_method_t method);
  298. /**
  299. * @brief Unregister all URI handlers with the specified uri string
  300. *
  301. * @param[in] handle handle to HTTPD server instance
  302. * @param[in] uri uri string specifying all handlers that need
  303. * to be deregisterd
  304. *
  305. * @return
  306. * - ESP_OK : On successfully deregistering all such handlers
  307. * - ESP_ERR_INVALID_ARG : Null arguments
  308. * - ESP_ERR_NOT_FOUND : No handler registered with specified uri string
  309. */
  310. esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char* uri);
  311. /** End of URI Handlers
  312. * @}
  313. */
  314. /* ************** Group: TX/RX ************** */
  315. /** @name TX / RX
  316. * Prototype for HTTPDs low-level send/recv functions
  317. * @{
  318. */
  319. /**
  320. * @brief Prototype for HTTPDs low-level send function
  321. * @return
  322. * - Bytes : The number of bytes sent successfully
  323. * - -VE : In case of error
  324. */
  325. typedef int (*httpd_send_func_t)(int sockfd, const char *buf, size_t buf_len, int flags);
  326. /**
  327. * @brief Prototype for HTTPDs low-level recv function
  328. * @return
  329. * - Bytes : The number of bytes received successfully
  330. * - -VE : In case of error
  331. */
  332. typedef int (*httpd_recv_func_t)(int sockfd, char *buf, size_t buf_len, int flags);
  333. /** End of TX / RX
  334. * @}
  335. */
  336. /* ************** Group: Request/Response ************** */
  337. /** @name Request / Response
  338. * APIs related to the data send/receive by URI handlers.
  339. * These APIs are supposed to be called only from the context of
  340. * a URI handler where httpd_req_t* request pointer is valid.
  341. * @{
  342. */
  343. /**
  344. * @brief Override web server's receive function
  345. *
  346. * This function overrides the web server's receive function. This same function is
  347. * used to read and parse HTTP headers as well as body.
  348. *
  349. * @note This API is supposed to be called only from the context of
  350. * a URI handler where httpd_req_t* request pointer is valid.
  351. *
  352. * @param[in] r The request being responded to
  353. * @param[in] recv_func The receive function to be set for this request
  354. *
  355. * @return
  356. * - ESP_OK : On successfully registering override
  357. * - ESP_ERR_INVALID_ARG : Null arguments
  358. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  359. */
  360. esp_err_t httpd_set_recv_override(httpd_req_t *r, httpd_recv_func_t recv_func);
  361. /**
  362. * @brief Override web server's send function
  363. *
  364. * This function overrides the web server's send function. This same function is
  365. * used to send out any response to any HTTP request.
  366. *
  367. * @note This API is supposed to be called only from the context of
  368. * a URI handler where httpd_req_t* request pointer is valid.
  369. *
  370. * @param[in] r The request being responded to
  371. * @param[in] send_func The send function to be set for this request
  372. *
  373. * @return
  374. * - ESP_OK : On successfully registering override
  375. * - ESP_ERR_INVALID_ARG : Null arguments
  376. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  377. */
  378. esp_err_t httpd_set_send_override(httpd_req_t *r, httpd_send_func_t send_func);
  379. /**
  380. * @brief Get the Socket Descriptor from the HTTP request
  381. *
  382. * This API will return the socket descriptor of the session for
  383. * which URI handler was executed on reception of HTTP request.
  384. * This is useful when user wants to call functions that require
  385. * session socket fd, from within a URI handler, ie. :
  386. * httpd_sess_get_ctx(),
  387. * httpd_trigger_sess_close(),
  388. * httpd_sess_update_timestamp().
  389. *
  390. * @note This API is supposed to be called only from the context of
  391. * a URI handler where httpd_req_t* request pointer is valid.
  392. *
  393. * @param[in] r The request whose socket descriptor should be found
  394. *
  395. * @return
  396. * - Socket descriptor : The socket descriptor for this request
  397. * - -1 : Invalid/NULL request pointer
  398. */
  399. int httpd_req_to_sockfd(httpd_req_t *r);
  400. /**
  401. * @brief API to read content data from the HTTP request
  402. *
  403. * This API will read HTTP content data from the HTTP request into
  404. * provided buffer. Use content_len provided in httpd_req_t structure
  405. * to know the length of data to be fetched. If content_len is too
  406. * large for the buffer then user may have to make multiple calls to
  407. * this function, each time fetching 'buf_len' number of bytes,
  408. * while the pointer to content data is incremented internally by
  409. * the same number.
  410. *
  411. * @note
  412. * - This API is supposed to be called only from the context of
  413. * a URI handler where httpd_req_t* request pointer is valid.
  414. * - If an error is returned, the URI handler must further return an error.
  415. * This will ensure that the erroneous socket is closed and cleaned up by
  416. * the web server.
  417. * - Presently Chunked Encoding is not supported
  418. *
  419. * @param[in] r The request being responded to
  420. * @param[in] buf Pointer to a buffer that the data will be read into
  421. * @param[in] buf_len Length of the buffer
  422. *
  423. * @return
  424. * - Bytes : Number of bytes read into the buffer successfully
  425. * - Zero : When no more data is left for read
  426. * - -1 : On raw recv error / Null arguments / Request pointer is invalid
  427. */
  428. int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len);
  429. /**
  430. * @brief Search for a field in request headers and
  431. * return the string length of it's value
  432. *
  433. * @note
  434. * - This API is supposed to be called only from the context of
  435. * a URI handler where httpd_req_t* request pointer is valid.
  436. * - Once httpd_resp_send() API is called all request headers
  437. * are purged, so request headers need be copied into separate
  438. * buffers if they are required later.
  439. *
  440. * @param[in] r The request being responded to
  441. * @param[in] field The header field to be searched in the request
  442. *
  443. * @return
  444. * - Length : If field is found in the request URL
  445. * - Zero : Field not found / Invalid request / Null arguments
  446. */
  447. size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field);
  448. /**
  449. * @brief Get the value string of a field from the request headers
  450. *
  451. * @note
  452. * - This API is supposed to be called only from the context of
  453. * a URI handler where httpd_req_t* request pointer is valid.
  454. * - Once httpd_resp_send() API is called all request headers
  455. * are purged, so request headers need be copied into separate
  456. * buffers if they are required later.
  457. * - If output size is greater than input, then the value is truncated,
  458. * accompanied by truncation error as return value.
  459. * - Use httpd_req_get_hdr_value_len() to know the right buffer length
  460. *
  461. * @param[in] r The request being responded to
  462. * @param[in] field The field to be searched in the header
  463. * @param[out] val Pointer to the buffer into which the value will be copied if the field is found
  464. * @param[in] val_size Size of the user buffer "val"
  465. *
  466. * @return
  467. * - ESP_OK : Field found in the request header and value string copied
  468. * - ESP_ERR_NOT_FOUND : Key not found
  469. * - ESP_ERR_INVALID_ARG : Null arguments
  470. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  471. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  472. */
  473. esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size);
  474. /**
  475. * @brief Get Query string length from the request URL
  476. *
  477. * @note This API is supposed to be called only from the context of
  478. * a URI handler where httpd_req_t* request pointer is valid
  479. *
  480. * @param[in] r The request being responded to
  481. *
  482. * @return
  483. * - Length : Query is found in the request URL
  484. * - Zero : Query not found / Null arguments / Invalid request
  485. */
  486. size_t httpd_req_get_url_query_len(httpd_req_t *r);
  487. /**
  488. * @brief Get Query string from the request URL
  489. *
  490. * @note
  491. * - Presently, the user can fetch the full URL query string, but decoding
  492. * will have to be performed by the user. Request headers can be read using
  493. * httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type:
  494. * application/x-www-form-urlencoded) and then the appropriate decoding
  495. * algorithm needs to be applied.
  496. * - This API is supposed to be called only from the context of
  497. * a URI handler where httpd_req_t* request pointer is valid
  498. * - If output size is greater than input, then the value is truncated,
  499. * accompanied by truncation error as return value
  500. * - Use httpd_req_get_url_query_len() to know the right buffer length
  501. *
  502. * @param[in] r The request being responded to
  503. * @param[out] buf Pointer to the buffer into which the query string will be copied (if found)
  504. * @param[in] buf_len Length of output buffer
  505. *
  506. * @return
  507. * - ESP_OK : Query is found in the request URL and copied to buffer
  508. * - ESP_ERR_NOT_FOUND : Query not found
  509. * - ESP_ERR_INVALID_ARG : Null arguments
  510. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  511. * - ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated
  512. */
  513. esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len);
  514. /**
  515. * @brief Helper function to get a URL query tag from a query
  516. * string of the type param1=val1&param2=val2
  517. *
  518. * @note
  519. * - The components of URL query string (keys and values) are not URLdecoded.
  520. * The user must check for 'Content-Type' field in the request headers and
  521. * then depending upon the specified encoding (URLencoded or otherwise) apply
  522. * the appropriate decoding algorithm.
  523. * - If actual value size is greater than val_size, then the value is truncated,
  524. * accompanied by truncation error as return value.
  525. *
  526. * @param[in] qry Pointer to query string
  527. * @param[in] key The key to be searched in the query string
  528. * @param[out] val Pointer to the buffer into which the value will be copied if the key is found
  529. * @param[in] val_size Size of the user buffer "val"
  530. *
  531. * @return
  532. * - ESP_OK : Key is found in the URL query string and copied to buffer
  533. * - ESP_ERR_NOT_FOUND : Key not found
  534. * - ESP_ERR_INVALID_ARG : Null arguments
  535. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  536. */
  537. esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size);
  538. /**
  539. * @brief API to send a complete HTTP response.
  540. *
  541. * This API will send the data as an HTTP response to the request.
  542. * This assumes that you have the entire response ready in a single
  543. * buffer. If you wish to send response in incremental chunks use
  544. * httpd_resp_send_chunk() instead.
  545. *
  546. * If no status code and content-type were set, by default this
  547. * will send 200 OK status code and content type as text/html.
  548. * You may call the following functions before this API to configure
  549. * the response headers :
  550. * httpd_resp_set_status() - for setting the HTTP status string,
  551. * httpd_resp_set_type() - for setting the Content Type,
  552. * httpd_resp_set_hdr() - for appending any additional field
  553. * value entries in the response header
  554. *
  555. * @note
  556. * - This API is supposed to be called only from the context of
  557. * a URI handler where httpd_req_t* request pointer is valid.
  558. * - Once this API is called, the request has been responded to.
  559. * - No additional data can then be sent for the request.
  560. * - Once this API is called, all request headers are purged, so
  561. * request headers need be copied into separate buffers if
  562. * they are required later.
  563. *
  564. * @param[in] r The request being responded to
  565. * @param[in] buf Buffer from where the content is to be fetched
  566. * @param[in] buf_len Length of the buffer
  567. *
  568. * @return
  569. * - ESP_OK : On successfully sending the response packet
  570. * - ESP_ERR_INVALID_ARG : Null request pointer
  571. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  572. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  573. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  574. */
  575. esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, size_t buf_len);
  576. /**
  577. * @brief API to send one HTTP chunk
  578. *
  579. * This API will send the data as an HTTP response to the
  580. * request. This API will use chunked-encoding and send the response
  581. * in the form of chunks. If you have the entire response contained in
  582. * a single buffer, please use httpd_resp_send() instead.
  583. *
  584. * If no status code and content-type were set, by default this will
  585. * send 200 OK status code and content type as text/html. You may
  586. * call the following functions before this API to configure the
  587. * response headers
  588. * httpd_resp_set_status() - for setting the HTTP status string,
  589. * httpd_resp_set_type() - for setting the Content Type,
  590. * httpd_resp_set_hdr() - for appending any additional field
  591. * value entries in the response header
  592. *
  593. * @note
  594. * - This API is supposed to be called only from the context of
  595. * a URI handler where httpd_req_t* request pointer is valid.
  596. * - When you are finished sending all your chunks, you must call
  597. * this function with buf_len as 0.
  598. * - Once this API is called, all request headers are purged, so
  599. * request headers need be copied into separate buffers if they
  600. * are required later.
  601. *
  602. * @param[in] r The request being responded to
  603. * @param[in] buf Pointer to a buffer that stores the data
  604. * @param[in] buf_len Length of the data from the buffer that should be sent out
  605. *
  606. * @return
  607. * - ESP_OK : On successfully sending the response packet chunk
  608. * - ESP_ERR_INVALID_ARG : Null request pointer
  609. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  610. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  611. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  612. */
  613. esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, size_t buf_len);
  614. /* Some commonly used status codes */
  615. #define HTTPD_200 "200 OK" /*!< HTTP Response 200 */
  616. #define HTTPD_204 "204 No Content" /*!< HTTP Response 204 */
  617. #define HTTPD_207 "207 Multi-Status" /*!< HTTP Response 207 */
  618. #define HTTPD_400 "400 Bad Request" /*!< HTTP Response 400 */
  619. #define HTTPD_404 "404 Not Found" /*!< HTTP Response 404 */
  620. #define HTTPD_500 "500 Internal Server Error" /*!< HTTP Response 500 */
  621. /**
  622. * @brief API to set the HTTP status code
  623. *
  624. * This API sets the status of the HTTP response to the value specified.
  625. * By default, the '200 OK' response is sent as the response.
  626. *
  627. * @note
  628. * - This API is supposed to be called only from the context of
  629. * a URI handler where httpd_req_t* request pointer is valid.
  630. * - This API only sets the status to this value. The status isn't
  631. * sent out until any of the send APIs is executed.
  632. * - Make sure that the lifetime of the status string is valid till
  633. * send function is called.
  634. *
  635. * @param[in] r The request being responded to
  636. * @param[in] status The HTTP status code of this response
  637. *
  638. * @return
  639. * - ESP_OK : On success
  640. * - ESP_ERR_INVALID_ARG : Null arguments
  641. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  642. */
  643. esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status);
  644. /* Some commonly used content types */
  645. #define HTTPD_TYPE_JSON "application/json" /*!< HTTP Content type JSON */
  646. #define HTTPD_TYPE_TEXT "text/html" /*!< HTTP Content type text/HTML */
  647. #define HTTPD_TYPE_OCTET "application/octet-stream" /*!< HTTP Content type octext-stream */
  648. /**
  649. * @brief API to set the HTTP content type
  650. *
  651. * This API sets the 'Content Type' field of the response.
  652. * The default content type is 'text/html'.
  653. *
  654. * @note
  655. * - This API is supposed to be called only from the context of
  656. * a URI handler where httpd_req_t* request pointer is valid.
  657. * - This API only sets the content type to this value. The type
  658. * isn't sent out until any of the send APIs is executed.
  659. * - Make sure that the lifetime of the type string is valid till
  660. * send function is called.
  661. *
  662. * @param[in] r The request being responded to
  663. * @param[in] type The Content Type of the response
  664. *
  665. * @return
  666. * - ESP_OK : On success
  667. * - ESP_ERR_INVALID_ARG : Null arguments
  668. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  669. */
  670. esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type);
  671. /**
  672. * @brief API to append any additional headers
  673. *
  674. * This API sets any additional header fields that need to be sent in the response.
  675. *
  676. * @note
  677. * - This API is supposed to be called only from the context of
  678. * a URI handler where httpd_req_t* request pointer is valid.
  679. * - The header isn't sent out until any of the send APIs is executed.
  680. * - The maximum allowed number of additional headers is limited to
  681. * value of max_resp_headers in config structure.
  682. * - Make sure that the lifetime of the field value strings are valid till
  683. * send function is called.
  684. *
  685. * @param[in] r The request being responded to
  686. * @param[in] field The field name of the HTTP header
  687. * @param[in] value The value of this HTTP header
  688. *
  689. * @return
  690. * - ESP_OK : On successfully appending new header
  691. * - ESP_ERR_INVALID_ARG : Null arguments
  692. * - ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed
  693. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  694. */
  695. esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value);
  696. /**
  697. * @brief Helper function for HTTP 404
  698. *
  699. * Send HTTP 404 message. If you wish to send additional data in the body of the
  700. * response, please use the lower-level functions directly.
  701. *
  702. * @note
  703. * - This API is supposed to be called only from the context of
  704. * a URI handler where httpd_req_t* request pointer is valid.
  705. * - Once this API is called, all request headers are purged, so
  706. * request headers need be copied into separate buffers if
  707. * they are required later.
  708. *
  709. * @param[in] r The request being responded to
  710. *
  711. * @return
  712. * - ESP_OK : On successfully sending the response packet
  713. * - ESP_ERR_INVALID_ARG : Null arguments
  714. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  715. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  716. */
  717. esp_err_t httpd_resp_send_404(httpd_req_t *r);
  718. /**
  719. * @brief Raw HTTP send
  720. *
  721. * Call this API if you wish to construct your custom response packet.
  722. * When using this, all essential header, eg. HTTP version, Status Code,
  723. * Content Type and Length, Encoding, etc. will have to be constructed
  724. * manually, and HTTP delimeters (CRLF) will need to be placed correctly
  725. * for separating sub-sections of the HTTP response packet.
  726. *
  727. * If the send override function is set, this API will end up
  728. * calling that function eventually to send data out.
  729. *
  730. * @note
  731. * - This API is supposed to be called only from the context of
  732. * a URI handler where httpd_req_t* request pointer is valid.
  733. * - Unless the response has the correct HTTP structure (which the
  734. * user must now ensure) it is not guaranteed that it will be
  735. * recognized by the client. For most cases, you wouldn't have
  736. * to call this API, but you would rather use either of :
  737. * httpd_resp_send(),
  738. * httpd_resp_send_chunk()
  739. *
  740. * @param[in] r The request being responded to
  741. * @param[in] buf Buffer from where the fully constructed packet is to be read
  742. * @param[in] buf_len Length of the buffer
  743. *
  744. * @return
  745. * - Bytes : Number of bytes that were sent successfully
  746. * - -1 : Error in raw send / Invalid request / Null arguments
  747. */
  748. int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len);
  749. /** End of Request / Response
  750. * @}
  751. */
  752. /* ************** Group: Session ************** */
  753. /** @name Session
  754. * Functions for controlling sessions and accessing context data
  755. * @{
  756. */
  757. /**
  758. * @brief Get session context from socket descriptor
  759. *
  760. * Typically if a session context is created, it is available to URI handlers
  761. * through the httpd_req_t structure. But, there are cases where the web
  762. * server's send/receive functions may require the context (for example, for
  763. * accessing keying information etc). Since the send/receive function only have
  764. * the socket descriptor at their disposal, this API provides them with a way to
  765. * retrieve the session context.
  766. *
  767. * @param[in] handle Handle to server returned by httpd_start
  768. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  769. *
  770. * @return
  771. * - void* : Pointer to the context associated with this session
  772. * - NULL : Empty context / Invalid handle / Invalid socket fd
  773. */
  774. void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd);
  775. /**
  776. * @brief Trigger an httpd session close externally
  777. *
  778. * @note Calling this API is only required in special circumstances wherein
  779. * some application requires to close an httpd client session asynchronously.
  780. *
  781. * @param[in] handle Handle to server returned by httpd_start
  782. * @param[in] sockfd The socket descriptor of the session to be closed
  783. *
  784. * @return
  785. * - ESP_OK : On successfully initiating closure
  786. * - ESP_FAIL : Failure to queue work
  787. * - ESP_ERR_NOT_FOUND : Socket fd not found
  788. * - ESP_ERR_INVALID_ARG : Null arguments
  789. */
  790. esp_err_t httpd_trigger_sess_close(httpd_handle_t handle, int sockfd);
  791. /**
  792. * @brief Update timestamp for a given socket
  793. *
  794. * Timestamps are internally associated with each session to monitor
  795. * how recently a session exchanged traffic. When LRU purge is enabled,
  796. * if a client is requesting for connection but maximum number of
  797. * sockets/sessions is reached, then the session having the earliest
  798. * timestamp is closed automatically.
  799. *
  800. * Updating the timestamp manually prevents the socket from being purged
  801. * due to the Least Recently Used (LRU) logic, even though it might not
  802. * have received traffic for some time. This is useful when all open
  803. * sockets/session are frequently exchanging traffic but the user specifically
  804. * wants one of the sessions to be kept open, irrespective of when it last
  805. * exchanged a packet.
  806. *
  807. * @note Calling this API is only necessary if the LRU Purge Enable option
  808. * is enabled.
  809. *
  810. * @param[in] handle Handle to server returned by httpd_start
  811. * @param[in] sockfd The socket descriptor of the session for which timestamp
  812. * is to be updated
  813. *
  814. * @return
  815. * - ESP_OK : Socket found and timestamp updated
  816. * - ESP_ERR_NOT_FOUND : Socket not found
  817. * - ESP_ERR_INVALID_ARG : Null arguments
  818. */
  819. esp_err_t httpd_sess_update_timestamp(httpd_handle_t handle, int sockfd);
  820. /** End of Session
  821. * @}
  822. */
  823. /* ************** Group: Work Queue ************** */
  824. /** @name Work Queue
  825. * APIs related to the HTTPD Work Queue
  826. * @{
  827. */
  828. /**
  829. * @brief Prototype of the HTTPD work function
  830. * Please refer to httpd_queue_work() for more details.
  831. * @param[in] arg The arguments for this work function
  832. */
  833. typedef void (*httpd_work_fn_t)(void *arg);
  834. /**
  835. * @brief Queue execution of a function in HTTPD's context
  836. *
  837. * This API queues a work function for asynchronous execution
  838. *
  839. * @note Some protocols require that the web server generate some asynchronous data
  840. * and send it to the persistently opened connection. This facility is for use
  841. * by such protocols.
  842. *
  843. * @param[in] handle Handle to server returned by httpd_start
  844. * @param[in] work Pointer to the function to be executed in the HTTPD's context
  845. * @param[in] arg Pointer to the arguments that should be passed to this function
  846. *
  847. * @return
  848. * - ESP_OK : On successfully queueing the work
  849. * - ESP_FAIL : Failure in ctrl socket
  850. * - ESP_ERR_INVALID_ARG : Null arguments
  851. */
  852. esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg);
  853. /** End of Group Work Queue
  854. * @}
  855. */
  856. #ifdef __cplusplus
  857. }
  858. #endif
  859. #endif /* ! _HTTP_SERVER_H_ */