http_server.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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. #define HTTPD_SOCK_ERR_FAIL -1
  320. #define HTTPD_SOCK_ERR_INVALID -2
  321. #define HTTPD_SOCK_ERR_TIMEOUT -3
  322. /**
  323. * @brief Prototype for HTTPDs low-level send function
  324. *
  325. * @note User specified send function must handle errors internally,
  326. * depending upon the set value of errno, and return specific
  327. * HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as
  328. * return value of httpd_send() function
  329. *
  330. * @return
  331. * - Bytes : The number of bytes sent successfully
  332. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  333. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
  334. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
  335. */
  336. typedef int (*httpd_send_func_t)(int sockfd, const char *buf, size_t buf_len, int flags);
  337. /**
  338. * @brief Prototype for HTTPDs low-level recv function
  339. *
  340. * @note User specified recv function must handle errors internally,
  341. * depending upon the set value of errno, and return specific
  342. * HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as
  343. * return value of httpd_req_recv() function
  344. *
  345. * @return
  346. * - Bytes : The number of bytes received successfully
  347. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  348. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
  349. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
  350. */
  351. typedef int (*httpd_recv_func_t)(int sockfd, char *buf, size_t buf_len, int flags);
  352. /** End of TX / RX
  353. * @}
  354. */
  355. /* ************** Group: Request/Response ************** */
  356. /** @name Request / Response
  357. * APIs related to the data send/receive by URI handlers.
  358. * These APIs are supposed to be called only from the context of
  359. * a URI handler where httpd_req_t* request pointer is valid.
  360. * @{
  361. */
  362. /**
  363. * @brief Override web server's receive function
  364. *
  365. * This function overrides the web server's receive function. This same function is
  366. * used to read and parse HTTP headers as well as body.
  367. *
  368. * @note This API is supposed to be called only from the context of
  369. * a URI handler where httpd_req_t* request pointer is valid.
  370. *
  371. * @param[in] r The request being responded to
  372. * @param[in] recv_func The receive function to be set for this request
  373. *
  374. * @return
  375. * - ESP_OK : On successfully registering override
  376. * - ESP_ERR_INVALID_ARG : Null arguments
  377. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  378. */
  379. esp_err_t httpd_set_recv_override(httpd_req_t *r, httpd_recv_func_t recv_func);
  380. /**
  381. * @brief Override web server's send function
  382. *
  383. * This function overrides the web server's send function. This same function is
  384. * used to send out any response to any HTTP request.
  385. *
  386. * @note This API is supposed to be called only from the context of
  387. * a URI handler where httpd_req_t* request pointer is valid.
  388. *
  389. * @param[in] r The request being responded to
  390. * @param[in] send_func The send function to be set for this request
  391. *
  392. * @return
  393. * - ESP_OK : On successfully registering override
  394. * - ESP_ERR_INVALID_ARG : Null arguments
  395. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  396. */
  397. esp_err_t httpd_set_send_override(httpd_req_t *r, httpd_send_func_t send_func);
  398. /**
  399. * @brief Get the Socket Descriptor from the HTTP request
  400. *
  401. * This API will return the socket descriptor of the session for
  402. * which URI handler was executed on reception of HTTP request.
  403. * This is useful when user wants to call functions that require
  404. * session socket fd, from within a URI handler, ie. :
  405. * httpd_sess_get_ctx(),
  406. * httpd_trigger_sess_close(),
  407. * httpd_sess_update_timestamp().
  408. *
  409. * @note This API is supposed to be called only from the context of
  410. * a URI handler where httpd_req_t* request pointer is valid.
  411. *
  412. * @param[in] r The request whose socket descriptor should be found
  413. *
  414. * @return
  415. * - Socket descriptor : The socket descriptor for this request
  416. * - -1 : Invalid/NULL request pointer
  417. */
  418. int httpd_req_to_sockfd(httpd_req_t *r);
  419. /**
  420. * @brief API to read content data from the HTTP request
  421. *
  422. * This API will read HTTP content data from the HTTP request into
  423. * provided buffer. Use content_len provided in httpd_req_t structure
  424. * to know the length of data to be fetched. If content_len is too
  425. * large for the buffer then user may have to make multiple calls to
  426. * this function, each time fetching 'buf_len' number of bytes,
  427. * while the pointer to content data is incremented internally by
  428. * the same number.
  429. *
  430. * @note
  431. * - This API is supposed to be called only from the context of
  432. * a URI handler where httpd_req_t* request pointer is valid.
  433. * - If an error is returned, the URI handler must further return an error.
  434. * This will ensure that the erroneous socket is closed and cleaned up by
  435. * the web server.
  436. * - Presently Chunked Encoding is not supported
  437. *
  438. * @param[in] r The request being responded to
  439. * @param[in] buf Pointer to a buffer that the data will be read into
  440. * @param[in] buf_len Length of the buffer
  441. *
  442. * @return
  443. * - Bytes : Number of bytes read into the buffer successfully
  444. * - Zero : When no more data is left for read
  445. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  446. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
  447. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
  448. */
  449. int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len);
  450. /**
  451. * @brief Search for a field in request headers and
  452. * return the string length of it's value
  453. *
  454. * @note
  455. * - This API is supposed to be called only from the context of
  456. * a URI handler where httpd_req_t* request pointer is valid.
  457. * - Once httpd_resp_send() API is called all request headers
  458. * are purged, so request headers need be copied into separate
  459. * buffers if they are required later.
  460. *
  461. * @param[in] r The request being responded to
  462. * @param[in] field The header field to be searched in the request
  463. *
  464. * @return
  465. * - Length : If field is found in the request URL
  466. * - Zero : Field not found / Invalid request / Null arguments
  467. */
  468. size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field);
  469. /**
  470. * @brief Get the value string of a field from the request headers
  471. *
  472. * @note
  473. * - This API is supposed to be called only from the context of
  474. * a URI handler where httpd_req_t* request pointer is valid.
  475. * - Once httpd_resp_send() API is called all request headers
  476. * are purged, so request headers need be copied into separate
  477. * buffers if they are required later.
  478. * - If output size is greater than input, then the value is truncated,
  479. * accompanied by truncation error as return value.
  480. * - Use httpd_req_get_hdr_value_len() to know the right buffer length
  481. *
  482. * @param[in] r The request being responded to
  483. * @param[in] field The field to be searched in the header
  484. * @param[out] val Pointer to the buffer into which the value will be copied if the field is found
  485. * @param[in] val_size Size of the user buffer "val"
  486. *
  487. * @return
  488. * - ESP_OK : Field found in the request header and value string copied
  489. * - ESP_ERR_NOT_FOUND : Key not found
  490. * - ESP_ERR_INVALID_ARG : Null arguments
  491. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  492. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  493. */
  494. esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size);
  495. /**
  496. * @brief Get Query string length from the request URL
  497. *
  498. * @note This API is supposed to be called only from the context of
  499. * a URI handler where httpd_req_t* request pointer is valid
  500. *
  501. * @param[in] r The request being responded to
  502. *
  503. * @return
  504. * - Length : Query is found in the request URL
  505. * - Zero : Query not found / Null arguments / Invalid request
  506. */
  507. size_t httpd_req_get_url_query_len(httpd_req_t *r);
  508. /**
  509. * @brief Get Query string from the request URL
  510. *
  511. * @note
  512. * - Presently, the user can fetch the full URL query string, but decoding
  513. * will have to be performed by the user. Request headers can be read using
  514. * httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type:
  515. * application/x-www-form-urlencoded) and then the appropriate decoding
  516. * algorithm needs to be applied.
  517. * - This API is supposed to be called only from the context of
  518. * a URI handler where httpd_req_t* request pointer is valid
  519. * - If output size is greater than input, then the value is truncated,
  520. * accompanied by truncation error as return value
  521. * - Use httpd_req_get_url_query_len() to know the right buffer length
  522. *
  523. * @param[in] r The request being responded to
  524. * @param[out] buf Pointer to the buffer into which the query string will be copied (if found)
  525. * @param[in] buf_len Length of output buffer
  526. *
  527. * @return
  528. * - ESP_OK : Query is found in the request URL and copied to buffer
  529. * - ESP_ERR_NOT_FOUND : Query not found
  530. * - ESP_ERR_INVALID_ARG : Null arguments
  531. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  532. * - ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated
  533. */
  534. esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len);
  535. /**
  536. * @brief Helper function to get a URL query tag from a query
  537. * string of the type param1=val1&param2=val2
  538. *
  539. * @note
  540. * - The components of URL query string (keys and values) are not URLdecoded.
  541. * The user must check for 'Content-Type' field in the request headers and
  542. * then depending upon the specified encoding (URLencoded or otherwise) apply
  543. * the appropriate decoding algorithm.
  544. * - If actual value size is greater than val_size, then the value is truncated,
  545. * accompanied by truncation error as return value.
  546. *
  547. * @param[in] qry Pointer to query string
  548. * @param[in] key The key to be searched in the query string
  549. * @param[out] val Pointer to the buffer into which the value will be copied if the key is found
  550. * @param[in] val_size Size of the user buffer "val"
  551. *
  552. * @return
  553. * - ESP_OK : Key is found in the URL query string and copied to buffer
  554. * - ESP_ERR_NOT_FOUND : Key not found
  555. * - ESP_ERR_INVALID_ARG : Null arguments
  556. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  557. */
  558. esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size);
  559. /**
  560. * @brief API to send a complete HTTP response.
  561. *
  562. * This API will send the data as an HTTP response to the request.
  563. * This assumes that you have the entire response ready in a single
  564. * buffer. If you wish to send response in incremental chunks use
  565. * httpd_resp_send_chunk() instead.
  566. *
  567. * If no status code and content-type were set, by default this
  568. * will send 200 OK status code and content type as text/html.
  569. * You may call the following functions before this API to configure
  570. * the response headers :
  571. * httpd_resp_set_status() - for setting the HTTP status string,
  572. * httpd_resp_set_type() - for setting the Content Type,
  573. * httpd_resp_set_hdr() - for appending any additional field
  574. * value entries in the response header
  575. *
  576. * @note
  577. * - This API is supposed to be called only from the context of
  578. * a URI handler where httpd_req_t* request pointer is valid.
  579. * - Once this API is called, the request has been responded to.
  580. * - No additional data can then be sent for the request.
  581. * - Once this API is called, all request headers are purged, so
  582. * request headers need be copied into separate buffers if
  583. * they are required later.
  584. *
  585. * @param[in] r The request being responded to
  586. * @param[in] buf Buffer from where the content is to be fetched
  587. * @param[in] buf_len Length of the buffer
  588. *
  589. * @return
  590. * - ESP_OK : On successfully sending the response packet
  591. * - ESP_ERR_INVALID_ARG : Null request pointer
  592. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  593. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  594. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  595. */
  596. esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, size_t buf_len);
  597. /**
  598. * @brief API to send one HTTP chunk
  599. *
  600. * This API will send the data as an HTTP response to the
  601. * request. This API will use chunked-encoding and send the response
  602. * in the form of chunks. If you have the entire response contained in
  603. * a single buffer, please use httpd_resp_send() instead.
  604. *
  605. * If no status code and content-type were set, by default this will
  606. * send 200 OK status code and content type as text/html. You may
  607. * call the following functions before this API to configure the
  608. * response headers
  609. * httpd_resp_set_status() - for setting the HTTP status string,
  610. * httpd_resp_set_type() - for setting the Content Type,
  611. * httpd_resp_set_hdr() - for appending any additional field
  612. * value entries in the response header
  613. *
  614. * @note
  615. * - This API is supposed to be called only from the context of
  616. * a URI handler where httpd_req_t* request pointer is valid.
  617. * - When you are finished sending all your chunks, you must call
  618. * this function with buf_len as 0.
  619. * - Once this API is called, all request headers are purged, so
  620. * request headers need be copied into separate buffers if they
  621. * are required later.
  622. *
  623. * @param[in] r The request being responded to
  624. * @param[in] buf Pointer to a buffer that stores the data
  625. * @param[in] buf_len Length of the data from the buffer that should be sent out
  626. *
  627. * @return
  628. * - ESP_OK : On successfully sending the response packet chunk
  629. * - ESP_ERR_INVALID_ARG : Null request pointer
  630. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  631. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  632. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  633. */
  634. esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, size_t buf_len);
  635. /* Some commonly used status codes */
  636. #define HTTPD_200 "200 OK" /*!< HTTP Response 200 */
  637. #define HTTPD_204 "204 No Content" /*!< HTTP Response 204 */
  638. #define HTTPD_207 "207 Multi-Status" /*!< HTTP Response 207 */
  639. #define HTTPD_400 "400 Bad Request" /*!< HTTP Response 400 */
  640. #define HTTPD_404 "404 Not Found" /*!< HTTP Response 404 */
  641. #define HTTPD_500 "500 Internal Server Error" /*!< HTTP Response 500 */
  642. /**
  643. * @brief API to set the HTTP status code
  644. *
  645. * This API sets the status of the HTTP response to the value specified.
  646. * By default, the '200 OK' response is sent as the response.
  647. *
  648. * @note
  649. * - This API is supposed to be called only from the context of
  650. * a URI handler where httpd_req_t* request pointer is valid.
  651. * - This API only sets the status to this value. The status isn't
  652. * sent out until any of the send APIs is executed.
  653. * - Make sure that the lifetime of the status string is valid till
  654. * send function is called.
  655. *
  656. * @param[in] r The request being responded to
  657. * @param[in] status The HTTP status code of this response
  658. *
  659. * @return
  660. * - ESP_OK : On success
  661. * - ESP_ERR_INVALID_ARG : Null arguments
  662. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  663. */
  664. esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status);
  665. /* Some commonly used content types */
  666. #define HTTPD_TYPE_JSON "application/json" /*!< HTTP Content type JSON */
  667. #define HTTPD_TYPE_TEXT "text/html" /*!< HTTP Content type text/HTML */
  668. #define HTTPD_TYPE_OCTET "application/octet-stream" /*!< HTTP Content type octext-stream */
  669. /**
  670. * @brief API to set the HTTP content type
  671. *
  672. * This API sets the 'Content Type' field of the response.
  673. * The default content type is 'text/html'.
  674. *
  675. * @note
  676. * - This API is supposed to be called only from the context of
  677. * a URI handler where httpd_req_t* request pointer is valid.
  678. * - This API only sets the content type to this value. The type
  679. * isn't sent out until any of the send APIs is executed.
  680. * - Make sure that the lifetime of the type string is valid till
  681. * send function is called.
  682. *
  683. * @param[in] r The request being responded to
  684. * @param[in] type The Content Type of the response
  685. *
  686. * @return
  687. * - ESP_OK : On success
  688. * - ESP_ERR_INVALID_ARG : Null arguments
  689. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  690. */
  691. esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type);
  692. /**
  693. * @brief API to append any additional headers
  694. *
  695. * This API sets any additional header fields that need to be sent in the response.
  696. *
  697. * @note
  698. * - This API is supposed to be called only from the context of
  699. * a URI handler where httpd_req_t* request pointer is valid.
  700. * - The header isn't sent out until any of the send APIs is executed.
  701. * - The maximum allowed number of additional headers is limited to
  702. * value of max_resp_headers in config structure.
  703. * - Make sure that the lifetime of the field value strings are valid till
  704. * send function is called.
  705. *
  706. * @param[in] r The request being responded to
  707. * @param[in] field The field name of the HTTP header
  708. * @param[in] value The value of this HTTP header
  709. *
  710. * @return
  711. * - ESP_OK : On successfully appending new header
  712. * - ESP_ERR_INVALID_ARG : Null arguments
  713. * - ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed
  714. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  715. */
  716. esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value);
  717. /**
  718. * @brief Helper function for HTTP 404
  719. *
  720. * Send HTTP 404 message. If you wish to send additional data in the body of the
  721. * response, please use the lower-level functions directly.
  722. *
  723. * @note
  724. * - This API is supposed to be called only from the context of
  725. * a URI handler where httpd_req_t* request pointer is valid.
  726. * - Once this API is called, all request headers are purged, so
  727. * request headers need be copied into separate buffers if
  728. * they are required later.
  729. *
  730. * @param[in] r The request being responded to
  731. *
  732. * @return
  733. * - ESP_OK : On successfully sending the response packet
  734. * - ESP_ERR_INVALID_ARG : Null arguments
  735. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  736. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  737. */
  738. esp_err_t httpd_resp_send_404(httpd_req_t *r);
  739. /**
  740. * @brief Raw HTTP send
  741. *
  742. * Call this API if you wish to construct your custom response packet.
  743. * When using this, all essential header, eg. HTTP version, Status Code,
  744. * Content Type and Length, Encoding, etc. will have to be constructed
  745. * manually, and HTTP delimeters (CRLF) will need to be placed correctly
  746. * for separating sub-sections of the HTTP response packet.
  747. *
  748. * If the send override function is set, this API will end up
  749. * calling that function eventually to send data out.
  750. *
  751. * @note
  752. * - This API is supposed to be called only from the context of
  753. * a URI handler where httpd_req_t* request pointer is valid.
  754. * - Unless the response has the correct HTTP structure (which the
  755. * user must now ensure) it is not guaranteed that it will be
  756. * recognized by the client. For most cases, you wouldn't have
  757. * to call this API, but you would rather use either of :
  758. * httpd_resp_send(),
  759. * httpd_resp_send_chunk()
  760. *
  761. * @param[in] r The request being responded to
  762. * @param[in] buf Buffer from where the fully constructed packet is to be read
  763. * @param[in] buf_len Length of the buffer
  764. *
  765. * @return
  766. * - Bytes : Number of bytes that were sent successfully
  767. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  768. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
  769. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
  770. */
  771. int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len);
  772. /** End of Request / Response
  773. * @}
  774. */
  775. /* ************** Group: Session ************** */
  776. /** @name Session
  777. * Functions for controlling sessions and accessing context data
  778. * @{
  779. */
  780. /**
  781. * @brief Get session context from socket descriptor
  782. *
  783. * Typically if a session context is created, it is available to URI handlers
  784. * through the httpd_req_t structure. But, there are cases where the web
  785. * server's send/receive functions may require the context (for example, for
  786. * accessing keying information etc). Since the send/receive function only have
  787. * the socket descriptor at their disposal, this API provides them with a way to
  788. * retrieve the session context.
  789. *
  790. * @param[in] handle Handle to server returned by httpd_start
  791. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  792. *
  793. * @return
  794. * - void* : Pointer to the context associated with this session
  795. * - NULL : Empty context / Invalid handle / Invalid socket fd
  796. */
  797. void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd);
  798. /**
  799. * @brief Trigger an httpd session close externally
  800. *
  801. * @note Calling this API is only required in special circumstances wherein
  802. * some application requires to close an httpd client session asynchronously.
  803. *
  804. * @param[in] handle Handle to server returned by httpd_start
  805. * @param[in] sockfd The socket descriptor of the session to be closed
  806. *
  807. * @return
  808. * - ESP_OK : On successfully initiating closure
  809. * - ESP_FAIL : Failure to queue work
  810. * - ESP_ERR_NOT_FOUND : Socket fd not found
  811. * - ESP_ERR_INVALID_ARG : Null arguments
  812. */
  813. esp_err_t httpd_trigger_sess_close(httpd_handle_t handle, int sockfd);
  814. /**
  815. * @brief Update timestamp for a given socket
  816. *
  817. * Timestamps are internally associated with each session to monitor
  818. * how recently a session exchanged traffic. When LRU purge is enabled,
  819. * if a client is requesting for connection but maximum number of
  820. * sockets/sessions is reached, then the session having the earliest
  821. * timestamp is closed automatically.
  822. *
  823. * Updating the timestamp manually prevents the socket from being purged
  824. * due to the Least Recently Used (LRU) logic, even though it might not
  825. * have received traffic for some time. This is useful when all open
  826. * sockets/session are frequently exchanging traffic but the user specifically
  827. * wants one of the sessions to be kept open, irrespective of when it last
  828. * exchanged a packet.
  829. *
  830. * @note Calling this API is only necessary if the LRU Purge Enable option
  831. * is enabled.
  832. *
  833. * @param[in] handle Handle to server returned by httpd_start
  834. * @param[in] sockfd The socket descriptor of the session for which timestamp
  835. * is to be updated
  836. *
  837. * @return
  838. * - ESP_OK : Socket found and timestamp updated
  839. * - ESP_ERR_NOT_FOUND : Socket not found
  840. * - ESP_ERR_INVALID_ARG : Null arguments
  841. */
  842. esp_err_t httpd_sess_update_timestamp(httpd_handle_t handle, int sockfd);
  843. /** End of Session
  844. * @}
  845. */
  846. /* ************** Group: Work Queue ************** */
  847. /** @name Work Queue
  848. * APIs related to the HTTPD Work Queue
  849. * @{
  850. */
  851. /**
  852. * @brief Prototype of the HTTPD work function
  853. * Please refer to httpd_queue_work() for more details.
  854. * @param[in] arg The arguments for this work function
  855. */
  856. typedef void (*httpd_work_fn_t)(void *arg);
  857. /**
  858. * @brief Queue execution of a function in HTTPD's context
  859. *
  860. * This API queues a work function for asynchronous execution
  861. *
  862. * @note Some protocols require that the web server generate some asynchronous data
  863. * and send it to the persistently opened connection. This facility is for use
  864. * by such protocols.
  865. *
  866. * @param[in] handle Handle to server returned by httpd_start
  867. * @param[in] work Pointer to the function to be executed in the HTTPD's context
  868. * @param[in] arg Pointer to the arguments that should be passed to this function
  869. *
  870. * @return
  871. * - ESP_OK : On successfully queueing the work
  872. * - ESP_FAIL : Failure in ctrl socket
  873. * - ESP_ERR_INVALID_ARG : Null arguments
  874. */
  875. esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg);
  876. /** End of Group Work Queue
  877. * @}
  878. */
  879. #ifdef __cplusplus
  880. }
  881. #endif
  882. #endif /* ! _HTTP_SERVER_H_ */