http_server.h 37 KB

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