esp_http_server.h 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  1. /*
  2. * SPDX-FileCopyrightText: 2018-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #ifndef _ESP_HTTP_SERVER_H_
  7. #define _ESP_HTTP_SERVER_H_
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <freertos/FreeRTOS.h>
  11. #include <freertos/task.h>
  12. #include <http_parser.h>
  13. #include <sdkconfig.h>
  14. #include <esp_err.h>
  15. #ifdef __cplusplus
  16. extern "C" {
  17. #endif
  18. #define ESP_HTTPD_DEF_CTRL_PORT (32768) /*!< HTTP Server control socket port*/
  19. /*
  20. note: esp_https_server.h includes a customized copy of this
  21. initializer that should be kept in sync
  22. */
  23. #define HTTPD_DEFAULT_CONFIG() { \
  24. .task_priority = tskIDLE_PRIORITY+5, \
  25. .stack_size = 4096, \
  26. .core_id = tskNO_AFFINITY, \
  27. .server_port = 80, \
  28. .ctrl_port = ESP_HTTPD_DEF_CTRL_PORT, \
  29. .max_open_sockets = 7, \
  30. .max_uri_handlers = 8, \
  31. .max_resp_headers = 8, \
  32. .backlog_conn = 5, \
  33. .lru_purge_enable = false, \
  34. .recv_wait_timeout = 5, \
  35. .send_wait_timeout = 5, \
  36. .global_user_ctx = NULL, \
  37. .global_user_ctx_free_fn = NULL, \
  38. .global_transport_ctx = NULL, \
  39. .global_transport_ctx_free_fn = NULL, \
  40. .enable_so_linger = false, \
  41. .linger_timeout = 0, \
  42. .keep_alive_enable = false, \
  43. .keep_alive_idle = 0, \
  44. .keep_alive_interval = 0, \
  45. .keep_alive_count = 0, \
  46. .open_fn = NULL, \
  47. .close_fn = NULL, \
  48. .uri_match_fn = NULL \
  49. }
  50. #define ESP_ERR_HTTPD_BASE (0xb000) /*!< Starting number of HTTPD error codes */
  51. #define ESP_ERR_HTTPD_HANDLERS_FULL (ESP_ERR_HTTPD_BASE + 1) /*!< All slots for registering URI handlers have been consumed */
  52. #define ESP_ERR_HTTPD_HANDLER_EXISTS (ESP_ERR_HTTPD_BASE + 2) /*!< URI handler with same method and target URI already registered */
  53. #define ESP_ERR_HTTPD_INVALID_REQ (ESP_ERR_HTTPD_BASE + 3) /*!< Invalid request pointer */
  54. #define ESP_ERR_HTTPD_RESULT_TRUNC (ESP_ERR_HTTPD_BASE + 4) /*!< Result string truncated */
  55. #define ESP_ERR_HTTPD_RESP_HDR (ESP_ERR_HTTPD_BASE + 5) /*!< Response header field larger than supported */
  56. #define ESP_ERR_HTTPD_RESP_SEND (ESP_ERR_HTTPD_BASE + 6) /*!< Error occured while sending response packet */
  57. #define ESP_ERR_HTTPD_ALLOC_MEM (ESP_ERR_HTTPD_BASE + 7) /*!< Failed to dynamically allocate memory for resource */
  58. #define ESP_ERR_HTTPD_TASK (ESP_ERR_HTTPD_BASE + 8) /*!< Failed to launch server task/thread */
  59. /* Symbol to be used as length parameter in httpd_resp_send APIs
  60. * for setting buffer length to string length */
  61. #define HTTPD_RESP_USE_STRLEN -1
  62. /* ************** Group: Initialization ************** */
  63. /** @name Initialization
  64. * APIs related to the Initialization of the web server
  65. * @{
  66. */
  67. /**
  68. * @brief HTTP Server Instance Handle
  69. *
  70. * Every instance of the server will have a unique handle.
  71. */
  72. typedef void* httpd_handle_t;
  73. /**
  74. * @brief HTTP Method Type wrapper over "enum http_method"
  75. * available in "http_parser" library
  76. */
  77. typedef enum http_method httpd_method_t;
  78. /**
  79. * @brief Prototype for freeing context data (if any)
  80. * @param[in] ctx object to free
  81. */
  82. typedef void (*httpd_free_ctx_fn_t)(void *ctx);
  83. /**
  84. * @brief Function prototype for opening a session.
  85. *
  86. * Called immediately after the socket was opened to set up the send/recv functions and
  87. * other parameters of the socket.
  88. *
  89. * @param[in] hd server instance
  90. * @param[in] sockfd session socket file descriptor
  91. * @return
  92. * - ESP_OK : On success
  93. * - Any value other than ESP_OK will signal the server to close the socket immediately
  94. */
  95. typedef esp_err_t (*httpd_open_func_t)(httpd_handle_t hd, int sockfd);
  96. /**
  97. * @brief Function prototype for closing a session.
  98. *
  99. * @note It's possible that the socket descriptor is invalid at this point, the function
  100. * is called for all terminated sessions. Ensure proper handling of return codes.
  101. *
  102. * @param[in] hd server instance
  103. * @param[in] sockfd session socket file descriptor
  104. */
  105. typedef void (*httpd_close_func_t)(httpd_handle_t hd, int sockfd);
  106. /**
  107. * @brief Function prototype for URI matching.
  108. *
  109. * @param[in] reference_uri URI/template with respect to which the other URI is matched
  110. * @param[in] uri_to_match URI/template being matched to the reference URI/template
  111. * @param[in] match_upto For specifying the actual length of `uri_to_match` up to
  112. * which the matching algorithm is to be applied (The maximum
  113. * value is `strlen(uri_to_match)`, independent of the length
  114. * of `reference_uri`)
  115. * @return true on match
  116. */
  117. typedef bool (*httpd_uri_match_func_t)(const char *reference_uri,
  118. const char *uri_to_match,
  119. size_t match_upto);
  120. /**
  121. * @brief HTTP Server Configuration Structure
  122. *
  123. * @note Use HTTPD_DEFAULT_CONFIG() to initialize the configuration
  124. * to a default value and then modify only those fields that are
  125. * specifically determined by the use case.
  126. */
  127. typedef struct httpd_config {
  128. unsigned task_priority; /*!< Priority of FreeRTOS task which runs the server */
  129. size_t stack_size; /*!< The maximum stack size allowed for the server task */
  130. BaseType_t core_id; /*!< The core the HTTP server task will run on */
  131. /**
  132. * TCP Port number for receiving and transmitting HTTP traffic
  133. */
  134. uint16_t server_port;
  135. /**
  136. * UDP Port number for asynchronously exchanging control signals
  137. * between various components of the server
  138. */
  139. uint16_t ctrl_port;
  140. uint16_t max_open_sockets; /*!< Max number of sockets/clients connected at any time (3 sockets are reserved for internal working of the HTTP server) */
  141. uint16_t max_uri_handlers; /*!< Maximum allowed uri handlers */
  142. uint16_t max_resp_headers; /*!< Maximum allowed additional headers in HTTP response */
  143. uint16_t backlog_conn; /*!< Number of backlog connections */
  144. bool lru_purge_enable; /*!< Purge "Least Recently Used" connection */
  145. uint16_t recv_wait_timeout; /*!< Timeout for recv function (in seconds)*/
  146. uint16_t send_wait_timeout; /*!< Timeout for send function (in seconds)*/
  147. /**
  148. * Global user context.
  149. *
  150. * This field can be used to store arbitrary user data within the server context.
  151. * The value can be retrieved using the server handle, available e.g. in the httpd_req_t struct.
  152. *
  153. * When shutting down, the server frees up the user context by
  154. * calling free() on the global_user_ctx field. If you wish to use a custom
  155. * function for freeing the global user context, please specify that here.
  156. */
  157. void * global_user_ctx;
  158. /**
  159. * Free function for global user context
  160. */
  161. httpd_free_ctx_fn_t global_user_ctx_free_fn;
  162. /**
  163. * Global transport context.
  164. *
  165. * Similar to global_user_ctx, but used for session encoding or encryption (e.g. to hold the SSL context).
  166. * It will be freed using free(), unless global_transport_ctx_free_fn is specified.
  167. */
  168. void * global_transport_ctx;
  169. /**
  170. * Free function for global transport context
  171. */
  172. httpd_free_ctx_fn_t global_transport_ctx_free_fn;
  173. bool enable_so_linger; /*!< bool to enable/disable linger */
  174. int linger_timeout; /*!< linger timeout (in seconds) */
  175. bool keep_alive_enable; /*!< Enable keep-alive timeout */
  176. int keep_alive_idle; /*!< Keep-alive idle time. Default is 5 (second) */
  177. int keep_alive_interval;/*!< Keep-alive interval time. Default is 5 (second) */
  178. int keep_alive_count; /*!< Keep-alive packet retry send count. Default is 3 counts */
  179. /**
  180. * Custom session opening callback.
  181. *
  182. * Called on a new session socket just after accept(), but before reading any data.
  183. *
  184. * This is an opportunity to set up e.g. SSL encryption using global_transport_ctx
  185. * and the send/recv/pending session overrides.
  186. *
  187. * If a context needs to be maintained between these functions, store it in the session using
  188. * httpd_sess_set_transport_ctx() and retrieve it later with httpd_sess_get_transport_ctx()
  189. *
  190. * Returning a value other than ESP_OK will immediately close the new socket.
  191. */
  192. httpd_open_func_t open_fn;
  193. /**
  194. * Custom session closing callback.
  195. *
  196. * Called when a session is deleted, before freeing user and transport contexts and before
  197. * closing the socket. This is a place for custom de-init code common to all sockets.
  198. *
  199. * The server will only close the socket if no custom session closing callback is set.
  200. * If a custom callback is used, `close(sockfd)` should be called in here for most cases.
  201. *
  202. * Set the user or transport context to NULL if it was freed here, so the server does not
  203. * try to free it again.
  204. *
  205. * This function is run for all terminated sessions, including sessions where the socket
  206. * was closed by the network stack - that is, the file descriptor may not be valid anymore.
  207. */
  208. httpd_close_func_t close_fn;
  209. /**
  210. * URI matcher function.
  211. *
  212. * Called when searching for a matching URI:
  213. * 1) whose request handler is to be executed right
  214. * after an HTTP request is successfully parsed
  215. * 2) in order to prevent duplication while registering
  216. * a new URI handler using `httpd_register_uri_handler()`
  217. *
  218. * Available options are:
  219. * 1) NULL : Internally do basic matching using `strncmp()`
  220. * 2) `httpd_uri_match_wildcard()` : URI wildcard matcher
  221. *
  222. * Users can implement their own matching functions (See description
  223. * of the `httpd_uri_match_func_t` function prototype)
  224. */
  225. httpd_uri_match_func_t uri_match_fn;
  226. } httpd_config_t;
  227. /**
  228. * @brief Starts the web server
  229. *
  230. * Create an instance of HTTP server and allocate memory/resources for it
  231. * depending upon the specified configuration.
  232. *
  233. * Example usage:
  234. * @code{c}
  235. *
  236. * //Function for starting the webserver
  237. * httpd_handle_t start_webserver(void)
  238. * {
  239. * // Generate default configuration
  240. * httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  241. *
  242. * // Empty handle to http_server
  243. * httpd_handle_t server = NULL;
  244. *
  245. * // Start the httpd server
  246. * if (httpd_start(&server, &config) == ESP_OK) {
  247. * // Register URI handlers
  248. * httpd_register_uri_handler(server, &uri_get);
  249. * httpd_register_uri_handler(server, &uri_post);
  250. * }
  251. * // If server failed to start, handle will be NULL
  252. * return server;
  253. * }
  254. *
  255. * @endcode
  256. *
  257. * @param[in] config Configuration for new instance of the server
  258. * @param[out] handle Handle to newly created instance of the server. NULL on error
  259. * @return
  260. * - ESP_OK : Instance created successfully
  261. * - ESP_ERR_INVALID_ARG : Null argument(s)
  262. * - ESP_ERR_HTTPD_ALLOC_MEM : Failed to allocate memory for instance
  263. * - ESP_ERR_HTTPD_TASK : Failed to launch server task
  264. */
  265. esp_err_t httpd_start(httpd_handle_t *handle, const httpd_config_t *config);
  266. /**
  267. * @brief Stops the web server
  268. *
  269. * Deallocates memory/resources used by an HTTP server instance and
  270. * deletes it. Once deleted the handle can no longer be used for accessing
  271. * the instance.
  272. *
  273. * Example usage:
  274. * @code{c}
  275. *
  276. * // Function for stopping the webserver
  277. * void stop_webserver(httpd_handle_t server)
  278. * {
  279. * // Ensure handle is non NULL
  280. * if (server != NULL) {
  281. * // Stop the httpd server
  282. * httpd_stop(server);
  283. * }
  284. * }
  285. *
  286. * @endcode
  287. *
  288. * @param[in] handle Handle to server returned by httpd_start
  289. * @return
  290. * - ESP_OK : Server stopped successfully
  291. * - ESP_ERR_INVALID_ARG : Handle argument is Null
  292. */
  293. esp_err_t httpd_stop(httpd_handle_t handle);
  294. /** End of Group Initialization
  295. * @}
  296. */
  297. /* ************** Group: URI Handlers ************** */
  298. /** @name URI Handlers
  299. * APIs related to the URI handlers
  300. * @{
  301. */
  302. /* Max supported HTTP request header length */
  303. #define HTTPD_MAX_REQ_HDR_LEN CONFIG_HTTPD_MAX_REQ_HDR_LEN
  304. /* Max supported HTTP request URI length */
  305. #define HTTPD_MAX_URI_LEN CONFIG_HTTPD_MAX_URI_LEN
  306. /**
  307. * @brief HTTP Request Data Structure
  308. */
  309. typedef struct httpd_req {
  310. httpd_handle_t handle; /*!< Handle to server instance */
  311. int method; /*!< The type of HTTP request, -1 if unsupported method */
  312. const char uri[HTTPD_MAX_URI_LEN + 1]; /*!< The URI of this request (1 byte extra for null termination) */
  313. size_t content_len; /*!< Length of the request body */
  314. void *aux; /*!< Internally used members */
  315. /**
  316. * User context pointer passed during URI registration.
  317. */
  318. void *user_ctx;
  319. /**
  320. * Session Context Pointer
  321. *
  322. * A session context. Contexts are maintained across 'sessions' for a
  323. * given open TCP connection. One session could have multiple request
  324. * responses. The web server will ensure that the context persists
  325. * across all these request and responses.
  326. *
  327. * By default, this is NULL. URI Handlers can set this to any meaningful
  328. * value.
  329. *
  330. * If the underlying socket gets closed, and this pointer is non-NULL,
  331. * the web server will free up the context by calling free(), unless
  332. * free_ctx function is set.
  333. */
  334. void *sess_ctx;
  335. /**
  336. * Pointer to free context hook
  337. *
  338. * Function to free session context
  339. *
  340. * If the web server's socket closes, it frees up the session context by
  341. * calling free() on the sess_ctx member. If you wish to use a custom
  342. * function for freeing the session context, please specify that here.
  343. */
  344. httpd_free_ctx_fn_t free_ctx;
  345. /**
  346. * Flag indicating if Session Context changes should be ignored
  347. *
  348. * By default, if you change the sess_ctx in some URI handler, the http server
  349. * will internally free the earlier context (if non NULL), after the URI handler
  350. * returns. If you want to manage the allocation/reallocation/freeing of
  351. * sess_ctx yourself, set this flag to true, so that the server will not
  352. * perform any checks on it. The context will be cleared by the server
  353. * (by calling free_ctx or free()) only if the socket gets closed.
  354. */
  355. bool ignore_sess_ctx_changes;
  356. } httpd_req_t;
  357. /**
  358. * @brief Structure for URI handler
  359. */
  360. typedef struct httpd_uri {
  361. const char *uri; /*!< The URI to handle */
  362. httpd_method_t method; /*!< Method supported by the URI */
  363. /**
  364. * Handler to call for supported request method. This must
  365. * return ESP_OK, or else the underlying socket will be closed.
  366. */
  367. esp_err_t (*handler)(httpd_req_t *r);
  368. /**
  369. * Pointer to user context data which will be available to handler
  370. */
  371. void *user_ctx;
  372. #ifdef CONFIG_HTTPD_WS_SUPPORT
  373. /**
  374. * Flag for indicating a WebSocket endpoint.
  375. * If this flag is true, then method must be HTTP_GET. Otherwise the handshake will not be handled.
  376. */
  377. bool is_websocket;
  378. /**
  379. * Flag indicating that control frames (PING, PONG, CLOSE) are also passed to the handler
  380. * This is used if a custom processing of the control frames is needed
  381. */
  382. bool handle_ws_control_frames;
  383. /**
  384. * Pointer to subprotocol supported by URI
  385. */
  386. const char *supported_subprotocol;
  387. #endif
  388. } httpd_uri_t;
  389. /**
  390. * @brief Registers a URI handler
  391. *
  392. * @note URI handlers can be registered in real time as long as the
  393. * server handle is valid.
  394. *
  395. * Example usage:
  396. * @code{c}
  397. *
  398. * esp_err_t my_uri_handler(httpd_req_t* req)
  399. * {
  400. * // Recv , Process and Send
  401. * ....
  402. * ....
  403. * ....
  404. *
  405. * // Fail condition
  406. * if (....) {
  407. * // Return fail to close session //
  408. * return ESP_FAIL;
  409. * }
  410. *
  411. * // On success
  412. * return ESP_OK;
  413. * }
  414. *
  415. * // URI handler structure
  416. * httpd_uri_t my_uri {
  417. * .uri = "/my_uri/path/xyz",
  418. * .method = HTTPD_GET,
  419. * .handler = my_uri_handler,
  420. * .user_ctx = NULL
  421. * };
  422. *
  423. * // Register handler
  424. * if (httpd_register_uri_handler(server_handle, &my_uri) != ESP_OK) {
  425. * // If failed to register handler
  426. * ....
  427. * }
  428. *
  429. * @endcode
  430. *
  431. * @param[in] handle handle to HTTPD server instance
  432. * @param[in] uri_handler pointer to handler that needs to be registered
  433. *
  434. * @return
  435. * - ESP_OK : On successfully registering the handler
  436. * - ESP_ERR_INVALID_ARG : Null arguments
  437. * - ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler
  438. * - ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and
  439. * method is already registered
  440. */
  441. esp_err_t httpd_register_uri_handler(httpd_handle_t handle,
  442. const httpd_uri_t *uri_handler);
  443. /**
  444. * @brief Unregister a URI handler
  445. *
  446. * @param[in] handle handle to HTTPD server instance
  447. * @param[in] uri URI string
  448. * @param[in] method HTTP method
  449. *
  450. * @return
  451. * - ESP_OK : On successfully deregistering the handler
  452. * - ESP_ERR_INVALID_ARG : Null arguments
  453. * - ESP_ERR_NOT_FOUND : Handler with specified URI and method not found
  454. */
  455. esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle,
  456. const char *uri, httpd_method_t method);
  457. /**
  458. * @brief Unregister all URI handlers with the specified uri string
  459. *
  460. * @param[in] handle handle to HTTPD server instance
  461. * @param[in] uri uri string specifying all handlers that need
  462. * to be deregisterd
  463. *
  464. * @return
  465. * - ESP_OK : On successfully deregistering all such handlers
  466. * - ESP_ERR_INVALID_ARG : Null arguments
  467. * - ESP_ERR_NOT_FOUND : No handler registered with specified uri string
  468. */
  469. esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char* uri);
  470. /** End of URI Handlers
  471. * @}
  472. */
  473. /* ************** Group: HTTP Error ************** */
  474. /** @name HTTP Error
  475. * Prototype for HTTP errors and error handling functions
  476. * @{
  477. */
  478. /**
  479. * @brief Error codes sent as HTTP response in case of errors
  480. * encountered during processing of an HTTP request
  481. */
  482. typedef enum {
  483. /* For any unexpected errors during parsing, like unexpected
  484. * state transitions, or unhandled errors.
  485. */
  486. HTTPD_500_INTERNAL_SERVER_ERROR = 0,
  487. /* For methods not supported by http_parser. Presently
  488. * http_parser halts parsing when such methods are
  489. * encountered and so the server responds with 400 Bad
  490. * Request error instead.
  491. */
  492. HTTPD_501_METHOD_NOT_IMPLEMENTED,
  493. /* When HTTP version is not 1.1 */
  494. HTTPD_505_VERSION_NOT_SUPPORTED,
  495. /* Returned when http_parser halts parsing due to incorrect
  496. * syntax of request, unsupported method in request URI or
  497. * due to chunked encoding / upgrade field present in headers
  498. */
  499. HTTPD_400_BAD_REQUEST,
  500. /* This response means the client must authenticate itself
  501. * to get the requested response.
  502. */
  503. HTTPD_401_UNAUTHORIZED,
  504. /* The client does not have access rights to the content,
  505. * so the server is refusing to give the requested resource.
  506. * Unlike 401, the client's identity is known to the server.
  507. */
  508. HTTPD_403_FORBIDDEN,
  509. /* When requested URI is not found */
  510. HTTPD_404_NOT_FOUND,
  511. /* When URI found, but method has no handler registered */
  512. HTTPD_405_METHOD_NOT_ALLOWED,
  513. /* Intended for recv timeout. Presently it's being sent
  514. * for other recv errors as well. Client should expect the
  515. * server to immediately close the connection after
  516. * responding with this.
  517. */
  518. HTTPD_408_REQ_TIMEOUT,
  519. /* Intended for responding to chunked encoding, which is
  520. * not supported currently. Though unhandled http_parser
  521. * callback for chunked request returns "400 Bad Request"
  522. */
  523. HTTPD_411_LENGTH_REQUIRED,
  524. /* URI length greater than CONFIG_HTTPD_MAX_URI_LEN */
  525. HTTPD_414_URI_TOO_LONG,
  526. /* Headers section larger than CONFIG_HTTPD_MAX_REQ_HDR_LEN */
  527. HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE,
  528. /* Used internally for retrieving the total count of errors */
  529. HTTPD_ERR_CODE_MAX
  530. } httpd_err_code_t;
  531. /**
  532. * @brief Function prototype for HTTP error handling.
  533. *
  534. * This function is executed upon HTTP errors generated during
  535. * internal processing of an HTTP request. This is used to override
  536. * the default behavior on error, which is to send HTTP error response
  537. * and close the underlying socket.
  538. *
  539. * @note
  540. * - If implemented, the server will not automatically send out HTTP
  541. * error response codes, therefore, httpd_resp_send_err() must be
  542. * invoked inside this function if user wishes to generate HTTP
  543. * error responses.
  544. * - When invoked, the validity of `uri`, `method`, `content_len`
  545. * and `user_ctx` fields of the httpd_req_t parameter is not
  546. * guaranteed as the HTTP request may be partially received/parsed.
  547. * - The function must return ESP_OK if underlying socket needs to
  548. * be kept open. Any other value will ensure that the socket is
  549. * closed. The return value is ignored when error is of type
  550. * `HTTPD_500_INTERNAL_SERVER_ERROR` and the socket closed anyway.
  551. *
  552. * @param[in] req HTTP request for which the error needs to be handled
  553. * @param[in] error Error type
  554. *
  555. * @return
  556. * - ESP_OK : error handled successful
  557. * - ESP_FAIL : failure indicates that the underlying socket needs to be closed
  558. */
  559. typedef esp_err_t (*httpd_err_handler_func_t)(httpd_req_t *req,
  560. httpd_err_code_t error);
  561. /**
  562. * @brief Function for registering HTTP error handlers
  563. *
  564. * This function maps a handler function to any supported error code
  565. * given by `httpd_err_code_t`. See prototype `httpd_err_handler_func_t`
  566. * above for details.
  567. *
  568. * @param[in] handle HTTP server handle
  569. * @param[in] error Error type
  570. * @param[in] handler_fn User implemented handler function
  571. * (Pass NULL to unset any previously set handler)
  572. *
  573. * @return
  574. * - ESP_OK : handler registered successfully
  575. * - ESP_ERR_INVALID_ARG : invalid error code or server handle
  576. */
  577. esp_err_t httpd_register_err_handler(httpd_handle_t handle,
  578. httpd_err_code_t error,
  579. httpd_err_handler_func_t handler_fn);
  580. /** End of HTTP Error
  581. * @}
  582. */
  583. /* ************** Group: TX/RX ************** */
  584. /** @name TX / RX
  585. * Prototype for HTTPDs low-level send/recv functions
  586. * @{
  587. */
  588. #define HTTPD_SOCK_ERR_FAIL -1
  589. #define HTTPD_SOCK_ERR_INVALID -2
  590. #define HTTPD_SOCK_ERR_TIMEOUT -3
  591. /**
  592. * @brief Prototype for HTTPDs low-level send function
  593. *
  594. * @note User specified send function must handle errors internally,
  595. * depending upon the set value of errno, and return specific
  596. * HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as
  597. * return value of httpd_send() function
  598. *
  599. * @param[in] hd server instance
  600. * @param[in] sockfd session socket file descriptor
  601. * @param[in] buf buffer with bytes to send
  602. * @param[in] buf_len data size
  603. * @param[in] flags flags for the send() function
  604. * @return
  605. * - Bytes : The number of bytes sent successfully
  606. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  607. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
  608. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
  609. */
  610. typedef int (*httpd_send_func_t)(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags);
  611. /**
  612. * @brief Prototype for HTTPDs low-level recv function
  613. *
  614. * @note User specified recv function must handle errors internally,
  615. * depending upon the set value of errno, and return specific
  616. * HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as
  617. * return value of httpd_req_recv() function
  618. *
  619. * @param[in] hd server instance
  620. * @param[in] sockfd session socket file descriptor
  621. * @param[in] buf buffer with bytes to send
  622. * @param[in] buf_len data size
  623. * @param[in] flags flags for the send() function
  624. * @return
  625. * - Bytes : The number of bytes received successfully
  626. * - 0 : Buffer length parameter is zero / connection closed by peer
  627. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  628. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
  629. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
  630. */
  631. typedef int (*httpd_recv_func_t)(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags);
  632. /**
  633. * @brief Prototype for HTTPDs low-level "get pending bytes" function
  634. *
  635. * @note User specified pending function must handle errors internally,
  636. * depending upon the set value of errno, and return specific
  637. * HTTPD_SOCK_ERR_ codes, which will be handled accordingly in
  638. * the server task.
  639. *
  640. * @param[in] hd server instance
  641. * @param[in] sockfd session socket file descriptor
  642. * @return
  643. * - Bytes : The number of bytes waiting to be received
  644. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  645. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket pending()
  646. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket pending()
  647. */
  648. typedef int (*httpd_pending_func_t)(httpd_handle_t hd, int sockfd);
  649. /** End of TX / RX
  650. * @}
  651. */
  652. /* ************** Group: Request/Response ************** */
  653. /** @name Request / Response
  654. * APIs related to the data send/receive by URI handlers.
  655. * These APIs are supposed to be called only from the context of
  656. * a URI handler where httpd_req_t* request pointer is valid.
  657. * @{
  658. */
  659. /**
  660. * @brief Override web server's receive function (by session FD)
  661. *
  662. * This function overrides the web server's receive function. This same function is
  663. * used to read HTTP request packets.
  664. *
  665. * @note This API is supposed to be called either from the context of
  666. * - an http session APIs where sockfd is a valid parameter
  667. * - a URI handler where sockfd is obtained using httpd_req_to_sockfd()
  668. *
  669. * @param[in] hd HTTPD instance handle
  670. * @param[in] sockfd Session socket FD
  671. * @param[in] recv_func The receive function to be set for this session
  672. *
  673. * @return
  674. * - ESP_OK : On successfully registering override
  675. * - ESP_ERR_INVALID_ARG : Null arguments
  676. */
  677. esp_err_t httpd_sess_set_recv_override(httpd_handle_t hd, int sockfd, httpd_recv_func_t recv_func);
  678. /**
  679. * @brief Override web server's send function (by session FD)
  680. *
  681. * This function overrides the web server's send function. This same function is
  682. * used to send out any response to any HTTP request.
  683. *
  684. * @note This API is supposed to be called either from the context of
  685. * - an http session APIs where sockfd is a valid parameter
  686. * - a URI handler where sockfd is obtained using httpd_req_to_sockfd()
  687. *
  688. * @param[in] hd HTTPD instance handle
  689. * @param[in] sockfd Session socket FD
  690. * @param[in] send_func The send function to be set for this session
  691. *
  692. * @return
  693. * - ESP_OK : On successfully registering override
  694. * - ESP_ERR_INVALID_ARG : Null arguments
  695. */
  696. esp_err_t httpd_sess_set_send_override(httpd_handle_t hd, int sockfd, httpd_send_func_t send_func);
  697. /**
  698. * @brief Override web server's pending function (by session FD)
  699. *
  700. * This function overrides the web server's pending function. This function is
  701. * used to test for pending bytes in a socket.
  702. *
  703. * @note This API is supposed to be called either from the context of
  704. * - an http session APIs where sockfd is a valid parameter
  705. * - a URI handler where sockfd is obtained using httpd_req_to_sockfd()
  706. *
  707. * @param[in] hd HTTPD instance handle
  708. * @param[in] sockfd Session socket FD
  709. * @param[in] pending_func The receive function to be set for this session
  710. *
  711. * @return
  712. * - ESP_OK : On successfully registering override
  713. * - ESP_ERR_INVALID_ARG : Null arguments
  714. */
  715. esp_err_t httpd_sess_set_pending_override(httpd_handle_t hd, int sockfd, httpd_pending_func_t pending_func);
  716. /**
  717. * @brief Get the Socket Descriptor from the HTTP request
  718. *
  719. * This API will return the socket descriptor of the session for
  720. * which URI handler was executed on reception of HTTP request.
  721. * This is useful when user wants to call functions that require
  722. * session socket fd, from within a URI handler, ie. :
  723. * httpd_sess_get_ctx(),
  724. * httpd_sess_trigger_close(),
  725. * httpd_sess_update_lru_counter().
  726. *
  727. * @note This API is supposed to be called only from the context of
  728. * a URI handler where httpd_req_t* request pointer is valid.
  729. *
  730. * @param[in] r The request whose socket descriptor should be found
  731. *
  732. * @return
  733. * - Socket descriptor : The socket descriptor for this request
  734. * - -1 : Invalid/NULL request pointer
  735. */
  736. int httpd_req_to_sockfd(httpd_req_t *r);
  737. /**
  738. * @brief API to read content data from the HTTP request
  739. *
  740. * This API will read HTTP content data from the HTTP request into
  741. * provided buffer. Use content_len provided in httpd_req_t structure
  742. * to know the length of data to be fetched. If content_len is too
  743. * large for the buffer then user may have to make multiple calls to
  744. * this function, each time fetching 'buf_len' number of bytes,
  745. * while the pointer to content data is incremented internally by
  746. * the same number.
  747. *
  748. * @note
  749. * - This API is supposed to be called only from the context of
  750. * a URI handler where httpd_req_t* request pointer is valid.
  751. * - If an error is returned, the URI handler must further return an error.
  752. * This will ensure that the erroneous socket is closed and cleaned up by
  753. * the web server.
  754. * - Presently Chunked Encoding is not supported
  755. *
  756. * @param[in] r The request being responded to
  757. * @param[in] buf Pointer to a buffer that the data will be read into
  758. * @param[in] buf_len Length of the buffer
  759. *
  760. * @return
  761. * - Bytes : Number of bytes read into the buffer successfully
  762. * - 0 : Buffer length parameter is zero / connection closed by peer
  763. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  764. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
  765. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
  766. */
  767. int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len);
  768. /**
  769. * @brief Search for a field in request headers and
  770. * return the string length of it's value
  771. *
  772. * @note
  773. * - This API is supposed to be called only from the context of
  774. * a URI handler where httpd_req_t* request pointer is valid.
  775. * - Once httpd_resp_send() API is called all request headers
  776. * are purged, so request headers need be copied into separate
  777. * buffers if they are required later.
  778. *
  779. * @param[in] r The request being responded to
  780. * @param[in] field The header field to be searched in the request
  781. *
  782. * @return
  783. * - Length : If field is found in the request URL
  784. * - Zero : Field not found / Invalid request / Null arguments
  785. */
  786. size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field);
  787. /**
  788. * @brief Get the value string of a field from the request headers
  789. *
  790. * @note
  791. * - This API is supposed to be called only from the context of
  792. * a URI handler where httpd_req_t* request pointer is valid.
  793. * - Once httpd_resp_send() API is called all request headers
  794. * are purged, so request headers need be copied into separate
  795. * buffers if they are required later.
  796. * - If output size is greater than input, then the value is truncated,
  797. * accompanied by truncation error as return value.
  798. * - Use httpd_req_get_hdr_value_len() to know the right buffer length
  799. *
  800. * @param[in] r The request being responded to
  801. * @param[in] field The field to be searched in the header
  802. * @param[out] val Pointer to the buffer into which the value will be copied if the field is found
  803. * @param[in] val_size Size of the user buffer "val"
  804. *
  805. * @return
  806. * - ESP_OK : Field found in the request header and value string copied
  807. * - ESP_ERR_NOT_FOUND : Key not found
  808. * - ESP_ERR_INVALID_ARG : Null arguments
  809. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  810. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  811. */
  812. esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size);
  813. /**
  814. * @brief Get Query string length from the request URL
  815. *
  816. * @note This API is supposed to be called only from the context of
  817. * a URI handler where httpd_req_t* request pointer is valid
  818. *
  819. * @param[in] r The request being responded to
  820. *
  821. * @return
  822. * - Length : Query is found in the request URL
  823. * - Zero : Query not found / Null arguments / Invalid request
  824. */
  825. size_t httpd_req_get_url_query_len(httpd_req_t *r);
  826. /**
  827. * @brief Get Query string from the request URL
  828. *
  829. * @note
  830. * - Presently, the user can fetch the full URL query string, but decoding
  831. * will have to be performed by the user. Request headers can be read using
  832. * httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type:
  833. * application/x-www-form-urlencoded) and then the appropriate decoding
  834. * algorithm needs to be applied.
  835. * - This API is supposed to be called only from the context of
  836. * a URI handler where httpd_req_t* request pointer is valid
  837. * - If output size is greater than input, then the value is truncated,
  838. * accompanied by truncation error as return value
  839. * - Prior to calling this function, one can use httpd_req_get_url_query_len()
  840. * to know the query string length beforehand and hence allocate the buffer
  841. * of right size (usually query string length + 1 for null termination)
  842. * for storing the query string
  843. *
  844. * @param[in] r The request being responded to
  845. * @param[out] buf Pointer to the buffer into which the query string will be copied (if found)
  846. * @param[in] buf_len Length of output buffer
  847. *
  848. * @return
  849. * - ESP_OK : Query is found in the request URL and copied to buffer
  850. * - ESP_ERR_NOT_FOUND : Query not found
  851. * - ESP_ERR_INVALID_ARG : Null arguments
  852. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  853. * - ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated
  854. */
  855. esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len);
  856. /**
  857. * @brief Helper function to get a URL query tag from a query
  858. * string of the type param1=val1&param2=val2
  859. *
  860. * @note
  861. * - The components of URL query string (keys and values) are not URLdecoded.
  862. * The user must check for 'Content-Type' field in the request headers and
  863. * then depending upon the specified encoding (URLencoded or otherwise) apply
  864. * the appropriate decoding algorithm.
  865. * - If actual value size is greater than val_size, then the value is truncated,
  866. * accompanied by truncation error as return value.
  867. *
  868. * @param[in] qry Pointer to query string
  869. * @param[in] key The key to be searched in the query string
  870. * @param[out] val Pointer to the buffer into which the value will be copied if the key is found
  871. * @param[in] val_size Size of the user buffer "val"
  872. *
  873. * @return
  874. * - ESP_OK : Key is found in the URL query string and copied to buffer
  875. * - ESP_ERR_NOT_FOUND : Key not found
  876. * - ESP_ERR_INVALID_ARG : Null arguments
  877. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  878. */
  879. esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size);
  880. /**
  881. * @brief Get the value string of a cookie value from the "Cookie" request headers by cookie name.
  882. *
  883. * @param[in] req Pointer to the HTTP request
  884. * @param[in] cookie_name The cookie name to be searched in the request
  885. * @param[out] val Pointer to the buffer into which the value of cookie will be copied if the cookie is found
  886. * @param[inout] val_size Pointer to size of the user buffer "val". This variable will contain cookie length if
  887. * ESP_OK is returned and required buffer length incase ESP_ERR_HTTPD_RESULT_TRUNC is returned.
  888. *
  889. * @return
  890. * - ESP_OK : Key is found in the cookie string and copied to buffer
  891. * - ESP_ERR_NOT_FOUND : Key not found
  892. * - ESP_ERR_INVALID_ARG : Null arguments
  893. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  894. * - ESP_ERR_NO_MEM : Memory allocation failure
  895. */
  896. esp_err_t httpd_req_get_cookie_val(httpd_req_t *req, const char *cookie_name, char *val, size_t *val_size);
  897. /**
  898. * @brief Test if a URI matches the given wildcard template.
  899. *
  900. * Template may end with "?" to make the previous character optional (typically a slash),
  901. * "*" for a wildcard match, and "?*" to make the previous character optional, and if present,
  902. * allow anything to follow.
  903. *
  904. * Example:
  905. * - * matches everything
  906. * - /foo/? matches /foo and /foo/
  907. * - /foo/\* (sans the backslash) matches /foo/ and /foo/bar, but not /foo or /fo
  908. * - /foo/?* or /foo/\*? (sans the backslash) matches /foo/, /foo/bar, and also /foo, but not /foox or /fo
  909. *
  910. * The special characters "?" and "*" anywhere else in the template will be taken literally.
  911. *
  912. * @param[in] uri_template URI template (pattern)
  913. * @param[in] uri_to_match URI to be matched
  914. * @param[in] match_upto how many characters of the URI buffer to test
  915. * (there may be trailing query string etc.)
  916. *
  917. * @return true if a match was found
  918. */
  919. bool httpd_uri_match_wildcard(const char *uri_template, const char *uri_to_match, size_t match_upto);
  920. /**
  921. * @brief API to send a complete HTTP response.
  922. *
  923. * This API will send the data as an HTTP response to the request.
  924. * This assumes that you have the entire response ready in a single
  925. * buffer. If you wish to send response in incremental chunks use
  926. * httpd_resp_send_chunk() instead.
  927. *
  928. * If no status code and content-type were set, by default this
  929. * will send 200 OK status code and content type as text/html.
  930. * You may call the following functions before this API to configure
  931. * the response headers :
  932. * httpd_resp_set_status() - for setting the HTTP status string,
  933. * httpd_resp_set_type() - for setting the Content Type,
  934. * httpd_resp_set_hdr() - for appending any additional field
  935. * value entries in the response header
  936. *
  937. * @note
  938. * - This API is supposed to be called only from the context of
  939. * a URI handler where httpd_req_t* request pointer is valid.
  940. * - Once this API is called, the request has been responded to.
  941. * - No additional data can then be sent for the request.
  942. * - Once this API is called, all request headers are purged, so
  943. * request headers need be copied into separate buffers if
  944. * they are required later.
  945. *
  946. * @param[in] r The request being responded to
  947. * @param[in] buf Buffer from where the content is to be fetched
  948. * @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
  949. *
  950. * @return
  951. * - ESP_OK : On successfully sending the response packet
  952. * - ESP_ERR_INVALID_ARG : Null request pointer
  953. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  954. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  955. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  956. */
  957. esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len);
  958. /**
  959. * @brief API to send one HTTP chunk
  960. *
  961. * This API will send the data as an HTTP response to the
  962. * request. This API will use chunked-encoding and send the response
  963. * in the form of chunks. If you have the entire response contained in
  964. * a single buffer, please use httpd_resp_send() instead.
  965. *
  966. * If no status code and content-type were set, by default this will
  967. * send 200 OK status code and content type as text/html. You may
  968. * call the following functions before this API to configure the
  969. * response headers
  970. * httpd_resp_set_status() - for setting the HTTP status string,
  971. * httpd_resp_set_type() - for setting the Content Type,
  972. * httpd_resp_set_hdr() - for appending any additional field
  973. * value entries in the response header
  974. *
  975. * @note
  976. * - This API is supposed to be called only from the context of
  977. * a URI handler where httpd_req_t* request pointer is valid.
  978. * - When you are finished sending all your chunks, you must call
  979. * this function with buf_len as 0.
  980. * - Once this API is called, all request headers are purged, so
  981. * request headers need be copied into separate buffers if they
  982. * are required later.
  983. *
  984. * @param[in] r The request being responded to
  985. * @param[in] buf Pointer to a buffer that stores the data
  986. * @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
  987. *
  988. * @return
  989. * - ESP_OK : On successfully sending the response packet chunk
  990. * - ESP_ERR_INVALID_ARG : Null request pointer
  991. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  992. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  993. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  994. */
  995. esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, ssize_t buf_len);
  996. /**
  997. * @brief API to send a complete string as HTTP response.
  998. *
  999. * This API simply calls http_resp_send with buffer length
  1000. * set to string length assuming the buffer contains a null
  1001. * terminated string
  1002. *
  1003. * @param[in] r The request being responded to
  1004. * @param[in] str String to be sent as response body
  1005. *
  1006. * @return
  1007. * - ESP_OK : On successfully sending the response packet
  1008. * - ESP_ERR_INVALID_ARG : Null request pointer
  1009. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  1010. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1011. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  1012. */
  1013. static inline esp_err_t httpd_resp_sendstr(httpd_req_t *r, const char *str) {
  1014. return httpd_resp_send(r, str, (str == NULL) ? 0 : HTTPD_RESP_USE_STRLEN);
  1015. }
  1016. /**
  1017. * @brief API to send a string as an HTTP response chunk.
  1018. *
  1019. * This API simply calls http_resp_send_chunk with buffer length
  1020. * set to string length assuming the buffer contains a null
  1021. * terminated string
  1022. *
  1023. * @param[in] r The request being responded to
  1024. * @param[in] str String to be sent as response body (NULL to finish response packet)
  1025. *
  1026. * @return
  1027. * - ESP_OK : On successfully sending the response packet
  1028. * - ESP_ERR_INVALID_ARG : Null request pointer
  1029. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  1030. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1031. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  1032. */
  1033. static inline esp_err_t httpd_resp_sendstr_chunk(httpd_req_t *r, const char *str) {
  1034. return httpd_resp_send_chunk(r, str, (str == NULL) ? 0 : HTTPD_RESP_USE_STRLEN);
  1035. }
  1036. /* Some commonly used status codes */
  1037. #define HTTPD_200 "200 OK" /*!< HTTP Response 200 */
  1038. #define HTTPD_204 "204 No Content" /*!< HTTP Response 204 */
  1039. #define HTTPD_207 "207 Multi-Status" /*!< HTTP Response 207 */
  1040. #define HTTPD_400 "400 Bad Request" /*!< HTTP Response 400 */
  1041. #define HTTPD_404 "404 Not Found" /*!< HTTP Response 404 */
  1042. #define HTTPD_408 "408 Request Timeout" /*!< HTTP Response 408 */
  1043. #define HTTPD_500 "500 Internal Server Error" /*!< HTTP Response 500 */
  1044. /**
  1045. * @brief API to set the HTTP status code
  1046. *
  1047. * This API sets the status of the HTTP response to the value specified.
  1048. * By default, the '200 OK' response is sent as the response.
  1049. *
  1050. * @note
  1051. * - This API is supposed to be called only from the context of
  1052. * a URI handler where httpd_req_t* request pointer is valid.
  1053. * - This API only sets the status to this value. The status isn't
  1054. * sent out until any of the send APIs is executed.
  1055. * - Make sure that the lifetime of the status string is valid till
  1056. * send function is called.
  1057. *
  1058. * @param[in] r The request being responded to
  1059. * @param[in] status The HTTP status code of this response
  1060. *
  1061. * @return
  1062. * - ESP_OK : On success
  1063. * - ESP_ERR_INVALID_ARG : Null arguments
  1064. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1065. */
  1066. esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status);
  1067. /* Some commonly used content types */
  1068. #define HTTPD_TYPE_JSON "application/json" /*!< HTTP Content type JSON */
  1069. #define HTTPD_TYPE_TEXT "text/html" /*!< HTTP Content type text/HTML */
  1070. #define HTTPD_TYPE_OCTET "application/octet-stream" /*!< HTTP Content type octext-stream */
  1071. /**
  1072. * @brief API to set the HTTP content type
  1073. *
  1074. * This API sets the 'Content Type' field of the response.
  1075. * The default content type is 'text/html'.
  1076. *
  1077. * @note
  1078. * - This API is supposed to be called only from the context of
  1079. * a URI handler where httpd_req_t* request pointer is valid.
  1080. * - This API only sets the content type to this value. The type
  1081. * isn't sent out until any of the send APIs is executed.
  1082. * - Make sure that the lifetime of the type string is valid till
  1083. * send function is called.
  1084. *
  1085. * @param[in] r The request being responded to
  1086. * @param[in] type The Content Type of the response
  1087. *
  1088. * @return
  1089. * - ESP_OK : On success
  1090. * - ESP_ERR_INVALID_ARG : Null arguments
  1091. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1092. */
  1093. esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type);
  1094. /**
  1095. * @brief API to append any additional headers
  1096. *
  1097. * This API sets any additional header fields that need to be sent in the response.
  1098. *
  1099. * @note
  1100. * - This API is supposed to be called only from the context of
  1101. * a URI handler where httpd_req_t* request pointer is valid.
  1102. * - The header isn't sent out until any of the send APIs is executed.
  1103. * - The maximum allowed number of additional headers is limited to
  1104. * value of max_resp_headers in config structure.
  1105. * - Make sure that the lifetime of the field value strings are valid till
  1106. * send function is called.
  1107. *
  1108. * @param[in] r The request being responded to
  1109. * @param[in] field The field name of the HTTP header
  1110. * @param[in] value The value of this HTTP header
  1111. *
  1112. * @return
  1113. * - ESP_OK : On successfully appending new header
  1114. * - ESP_ERR_INVALID_ARG : Null arguments
  1115. * - ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed
  1116. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1117. */
  1118. esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value);
  1119. /**
  1120. * @brief For sending out error code in response to HTTP request.
  1121. *
  1122. * @note
  1123. * - This API is supposed to be called only from the context of
  1124. * a URI handler where httpd_req_t* request pointer is valid.
  1125. * - Once this API is called, all request headers are purged, so
  1126. * request headers need be copied into separate buffers if
  1127. * they are required later.
  1128. * - If you wish to send additional data in the body of the
  1129. * response, please use the lower-level functions directly.
  1130. *
  1131. * @param[in] req Pointer to the HTTP request for which the response needs to be sent
  1132. * @param[in] error Error type to send
  1133. * @param[in] msg Error message string (pass NULL for default message)
  1134. *
  1135. * @return
  1136. * - ESP_OK : On successfully sending the response packet
  1137. * - ESP_ERR_INVALID_ARG : Null arguments
  1138. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1139. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1140. */
  1141. esp_err_t httpd_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *msg);
  1142. /**
  1143. * @brief Helper function for HTTP 404
  1144. *
  1145. * Send HTTP 404 message. If you wish to send additional data in the body of the
  1146. * response, please use the lower-level functions directly.
  1147. *
  1148. * @note
  1149. * - This API is supposed to be called only from the context of
  1150. * a URI handler where httpd_req_t* request pointer is valid.
  1151. * - Once this API is called, all request headers are purged, so
  1152. * request headers need be copied into separate buffers if
  1153. * they are required later.
  1154. *
  1155. * @param[in] r The request being responded to
  1156. *
  1157. * @return
  1158. * - ESP_OK : On successfully sending the response packet
  1159. * - ESP_ERR_INVALID_ARG : Null arguments
  1160. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1161. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1162. */
  1163. static inline esp_err_t httpd_resp_send_404(httpd_req_t *r) {
  1164. return httpd_resp_send_err(r, HTTPD_404_NOT_FOUND, NULL);
  1165. }
  1166. /**
  1167. * @brief Helper function for HTTP 408
  1168. *
  1169. * Send HTTP 408 message. If you wish to send additional data in the body of the
  1170. * response, please use the lower-level functions directly.
  1171. *
  1172. * @note
  1173. * - This API is supposed to be called only from the context of
  1174. * a URI handler where httpd_req_t* request pointer is valid.
  1175. * - Once this API is called, all request headers are purged, so
  1176. * request headers need be copied into separate buffers if
  1177. * they are required later.
  1178. *
  1179. * @param[in] r The request being responded to
  1180. *
  1181. * @return
  1182. * - ESP_OK : On successfully sending the response packet
  1183. * - ESP_ERR_INVALID_ARG : Null arguments
  1184. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1185. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1186. */
  1187. static inline esp_err_t httpd_resp_send_408(httpd_req_t *r) {
  1188. return httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT, NULL);
  1189. }
  1190. /**
  1191. * @brief Helper function for HTTP 500
  1192. *
  1193. * Send HTTP 500 message. If you wish to send additional data in the body of the
  1194. * response, please use the lower-level functions directly.
  1195. *
  1196. * @note
  1197. * - This API is supposed to be called only from the context of
  1198. * a URI handler where httpd_req_t* request pointer is valid.
  1199. * - Once this API is called, all request headers are purged, so
  1200. * request headers need be copied into separate buffers if
  1201. * they are required later.
  1202. *
  1203. * @param[in] r The request being responded to
  1204. *
  1205. * @return
  1206. * - ESP_OK : On successfully sending the response packet
  1207. * - ESP_ERR_INVALID_ARG : Null arguments
  1208. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1209. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1210. */
  1211. static inline esp_err_t httpd_resp_send_500(httpd_req_t *r) {
  1212. return httpd_resp_send_err(r, HTTPD_500_INTERNAL_SERVER_ERROR, NULL);
  1213. }
  1214. /**
  1215. * @brief Raw HTTP send
  1216. *
  1217. * Call this API if you wish to construct your custom response packet.
  1218. * When using this, all essential header, eg. HTTP version, Status Code,
  1219. * Content Type and Length, Encoding, etc. will have to be constructed
  1220. * manually, and HTTP delimeters (CRLF) will need to be placed correctly
  1221. * for separating sub-sections of the HTTP response packet.
  1222. *
  1223. * If the send override function is set, this API will end up
  1224. * calling that function eventually to send data out.
  1225. *
  1226. * @note
  1227. * - This API is supposed to be called only from the context of
  1228. * a URI handler where httpd_req_t* request pointer is valid.
  1229. * - Unless the response has the correct HTTP structure (which the
  1230. * user must now ensure) it is not guaranteed that it will be
  1231. * recognized by the client. For most cases, you wouldn't have
  1232. * to call this API, but you would rather use either of :
  1233. * httpd_resp_send(),
  1234. * httpd_resp_send_chunk()
  1235. *
  1236. * @param[in] r The request being responded to
  1237. * @param[in] buf Buffer from where the fully constructed packet is to be read
  1238. * @param[in] buf_len Length of the buffer
  1239. *
  1240. * @return
  1241. * - Bytes : Number of bytes that were sent successfully
  1242. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  1243. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
  1244. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
  1245. */
  1246. int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len);
  1247. /**
  1248. * A low level API to send data on a given socket
  1249. *
  1250. * @note This API is not recommended to be used in any request handler.
  1251. * Use this only for advanced use cases, wherein some asynchronous
  1252. * data is to be sent over a socket.
  1253. *
  1254. * This internally calls the default send function, or the function registered by
  1255. * httpd_sess_set_send_override().
  1256. *
  1257. * @param[in] hd server instance
  1258. * @param[in] sockfd session socket file descriptor
  1259. * @param[in] buf buffer with bytes to send
  1260. * @param[in] buf_len data size
  1261. * @param[in] flags flags for the send() function
  1262. * @return
  1263. * - Bytes : The number of bytes sent successfully
  1264. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  1265. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
  1266. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
  1267. */
  1268. int httpd_socket_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags);
  1269. /**
  1270. * A low level API to receive data from a given socket
  1271. *
  1272. * @note This API is not recommended to be used in any request handler.
  1273. * Use this only for advanced use cases, wherein some asynchronous
  1274. * communication is required.
  1275. *
  1276. * This internally calls the default recv function, or the function registered by
  1277. * httpd_sess_set_recv_override().
  1278. *
  1279. * @param[in] hd server instance
  1280. * @param[in] sockfd session socket file descriptor
  1281. * @param[in] buf buffer with bytes to send
  1282. * @param[in] buf_len data size
  1283. * @param[in] flags flags for the send() function
  1284. * @return
  1285. * - Bytes : The number of bytes received successfully
  1286. * - 0 : Buffer length parameter is zero / connection closed by peer
  1287. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  1288. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
  1289. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
  1290. */
  1291. int httpd_socket_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags);
  1292. /** End of Request / Response
  1293. * @}
  1294. */
  1295. /* ************** Group: Session ************** */
  1296. /** @name Session
  1297. * Functions for controlling sessions and accessing context data
  1298. * @{
  1299. */
  1300. /**
  1301. * @brief Get session context from socket descriptor
  1302. *
  1303. * Typically if a session context is created, it is available to URI handlers
  1304. * through the httpd_req_t structure. But, there are cases where the web
  1305. * server's send/receive functions may require the context (for example, for
  1306. * accessing keying information etc). Since the send/receive function only have
  1307. * the socket descriptor at their disposal, this API provides them with a way to
  1308. * retrieve the session context.
  1309. *
  1310. * @param[in] handle Handle to server returned by httpd_start
  1311. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1312. *
  1313. * @return
  1314. * - void* : Pointer to the context associated with this session
  1315. * - NULL : Empty context / Invalid handle / Invalid socket fd
  1316. */
  1317. void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd);
  1318. /**
  1319. * @brief Set session context by socket descriptor
  1320. *
  1321. * @param[in] handle Handle to server returned by httpd_start
  1322. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1323. * @param[in] ctx Context object to assign to the session
  1324. * @param[in] free_fn Function that should be called to free the context
  1325. */
  1326. void httpd_sess_set_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn);
  1327. /**
  1328. * @brief Get session 'transport' context by socket descriptor
  1329. * @see httpd_sess_get_ctx()
  1330. *
  1331. * This context is used by the send/receive functions, for example to manage SSL context.
  1332. *
  1333. * @param[in] handle Handle to server returned by httpd_start
  1334. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1335. * @return
  1336. * - void* : Pointer to the transport context associated with this session
  1337. * - NULL : Empty context / Invalid handle / Invalid socket fd
  1338. */
  1339. void *httpd_sess_get_transport_ctx(httpd_handle_t handle, int sockfd);
  1340. /**
  1341. * @brief Set session 'transport' context by socket descriptor
  1342. * @see httpd_sess_set_ctx()
  1343. *
  1344. * @param[in] handle Handle to server returned by httpd_start
  1345. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1346. * @param[in] ctx Transport context object to assign to the session
  1347. * @param[in] free_fn Function that should be called to free the transport context
  1348. */
  1349. void httpd_sess_set_transport_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn);
  1350. /**
  1351. * @brief Get HTTPD global user context (it was set in the server config struct)
  1352. *
  1353. * @param[in] handle Handle to server returned by httpd_start
  1354. * @return global user context
  1355. */
  1356. void *httpd_get_global_user_ctx(httpd_handle_t handle);
  1357. /**
  1358. * @brief Get HTTPD global transport context (it was set in the server config struct)
  1359. *
  1360. * @param[in] handle Handle to server returned by httpd_start
  1361. * @return global transport context
  1362. */
  1363. void *httpd_get_global_transport_ctx(httpd_handle_t handle);
  1364. /**
  1365. * @brief Trigger an httpd session close externally
  1366. *
  1367. * @note Calling this API is only required in special circumstances wherein
  1368. * some application requires to close an httpd client session asynchronously.
  1369. *
  1370. * @param[in] handle Handle to server returned by httpd_start
  1371. * @param[in] sockfd The socket descriptor of the session to be closed
  1372. *
  1373. * @return
  1374. * - ESP_OK : On successfully initiating closure
  1375. * - ESP_FAIL : Failure to queue work
  1376. * - ESP_ERR_NOT_FOUND : Socket fd not found
  1377. * - ESP_ERR_INVALID_ARG : Null arguments
  1378. */
  1379. esp_err_t httpd_sess_trigger_close(httpd_handle_t handle, int sockfd);
  1380. /**
  1381. * @brief Update LRU counter for a given socket
  1382. *
  1383. * LRU Counters are internally associated with each session to monitor
  1384. * how recently a session exchanged traffic. When LRU purge is enabled,
  1385. * if a client is requesting for connection but maximum number of
  1386. * sockets/sessions is reached, then the session having the earliest
  1387. * LRU counter is closed automatically.
  1388. *
  1389. * Updating the LRU counter manually prevents the socket from being purged
  1390. * due to the Least Recently Used (LRU) logic, even though it might not
  1391. * have received traffic for some time. This is useful when all open
  1392. * sockets/session are frequently exchanging traffic but the user specifically
  1393. * wants one of the sessions to be kept open, irrespective of when it last
  1394. * exchanged a packet.
  1395. *
  1396. * @note Calling this API is only necessary if the LRU Purge Enable option
  1397. * is enabled.
  1398. *
  1399. * @param[in] handle Handle to server returned by httpd_start
  1400. * @param[in] sockfd The socket descriptor of the session for which LRU counter
  1401. * is to be updated
  1402. *
  1403. * @return
  1404. * - ESP_OK : Socket found and LRU counter updated
  1405. * - ESP_ERR_NOT_FOUND : Socket not found
  1406. * - ESP_ERR_INVALID_ARG : Null arguments
  1407. */
  1408. esp_err_t httpd_sess_update_lru_counter(httpd_handle_t handle, int sockfd);
  1409. /**
  1410. * @brief Returns list of current socket descriptors of active sessions
  1411. *
  1412. * @param[in] handle Handle to server returned by httpd_start
  1413. * @param[in,out] fds In: Size of provided client_fds array
  1414. * Out: Number of valid client fds returned in client_fds,
  1415. * @param[out] client_fds Array of client fds
  1416. *
  1417. * @note Size of provided array has to be equal or greater then maximum number of opened
  1418. * sockets, configured upon initialization with max_open_sockets field in
  1419. * httpd_config_t structure.
  1420. *
  1421. * @return
  1422. * - ESP_OK : Successfully retrieved session list
  1423. * - ESP_ERR_INVALID_ARG : Wrong arguments or list is longer than provided array
  1424. */
  1425. esp_err_t httpd_get_client_list(httpd_handle_t handle, size_t *fds, int *client_fds);
  1426. /** End of Session
  1427. * @}
  1428. */
  1429. /* ************** Group: Work Queue ************** */
  1430. /** @name Work Queue
  1431. * APIs related to the HTTPD Work Queue
  1432. * @{
  1433. */
  1434. /**
  1435. * @brief Prototype of the HTTPD work function
  1436. * Please refer to httpd_queue_work() for more details.
  1437. * @param[in] arg The arguments for this work function
  1438. */
  1439. typedef void (*httpd_work_fn_t)(void *arg);
  1440. /**
  1441. * @brief Queue execution of a function in HTTPD's context
  1442. *
  1443. * This API queues a work function for asynchronous execution
  1444. *
  1445. * @note Some protocols require that the web server generate some asynchronous data
  1446. * and send it to the persistently opened connection. This facility is for use
  1447. * by such protocols.
  1448. *
  1449. * @param[in] handle Handle to server returned by httpd_start
  1450. * @param[in] work Pointer to the function to be executed in the HTTPD's context
  1451. * @param[in] arg Pointer to the arguments that should be passed to this function
  1452. *
  1453. * @return
  1454. * - ESP_OK : On successfully queueing the work
  1455. * - ESP_FAIL : Failure in ctrl socket
  1456. * - ESP_ERR_INVALID_ARG : Null arguments
  1457. */
  1458. esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg);
  1459. /** End of Group Work Queue
  1460. * @}
  1461. */
  1462. /* ************** Group: WebSocket ************** */
  1463. /** @name WebSocket
  1464. * Functions and structs for WebSocket server
  1465. * @{
  1466. */
  1467. #ifdef CONFIG_HTTPD_WS_SUPPORT
  1468. /**
  1469. * @brief Enum for WebSocket packet types (Opcode in the header)
  1470. * @note Please refer to RFC6455 Section 5.4 for more details
  1471. */
  1472. typedef enum {
  1473. HTTPD_WS_TYPE_CONTINUE = 0x0,
  1474. HTTPD_WS_TYPE_TEXT = 0x1,
  1475. HTTPD_WS_TYPE_BINARY = 0x2,
  1476. HTTPD_WS_TYPE_CLOSE = 0x8,
  1477. HTTPD_WS_TYPE_PING = 0x9,
  1478. HTTPD_WS_TYPE_PONG = 0xA
  1479. } httpd_ws_type_t;
  1480. /**
  1481. * @brief Enum for client info description
  1482. */
  1483. typedef enum {
  1484. HTTPD_WS_CLIENT_INVALID = 0x0,
  1485. HTTPD_WS_CLIENT_HTTP = 0x1,
  1486. HTTPD_WS_CLIENT_WEBSOCKET = 0x2,
  1487. } httpd_ws_client_info_t;
  1488. /**
  1489. * @brief WebSocket frame format
  1490. */
  1491. typedef struct httpd_ws_frame {
  1492. bool final; /*!< Final frame:
  1493. For received frames this field indicates whether the `FIN` flag was set.
  1494. For frames to be transmitted, this field is only used if the `fragmented`
  1495. option is set as well. If `fragmented` is false, the `FIN` flag is set
  1496. by default, marking the ws_frame as a complete/unfragmented message
  1497. (esp_http_server doesn't automatically fragment messages) */
  1498. bool fragmented; /*!< Indication that the frame allocated for transmission is a message fragment,
  1499. so the `FIN` flag is set manually according to the `final` option.
  1500. This flag is never set for received messages */
  1501. httpd_ws_type_t type; /*!< WebSocket frame type */
  1502. uint8_t *payload; /*!< Pre-allocated data buffer */
  1503. size_t len; /*!< Length of the WebSocket data */
  1504. } httpd_ws_frame_t;
  1505. /**
  1506. * @brief Transfer complete callback
  1507. */
  1508. typedef void (*transfer_complete_cb)(esp_err_t err, int socket, void *arg);
  1509. /**
  1510. * @brief Receive and parse a WebSocket frame
  1511. *
  1512. * @note Calling httpd_ws_recv_frame() with max_len as 0 will give actual frame size in pkt->len.
  1513. * The user can dynamically allocate space for pkt->payload as per this length and call httpd_ws_recv_frame() again to get the actual data.
  1514. * Please refer to the corresponding example for usage.
  1515. *
  1516. * @param[in] req Current request
  1517. * @param[out] pkt WebSocket packet
  1518. * @param[in] max_len Maximum length for receive
  1519. * @return
  1520. * - ESP_OK : On successful
  1521. * - ESP_FAIL : Socket errors occurs
  1522. * - ESP_ERR_INVALID_STATE : Handshake was already done beforehand
  1523. * - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket)
  1524. */
  1525. esp_err_t httpd_ws_recv_frame(httpd_req_t *req, httpd_ws_frame_t *pkt, size_t max_len);
  1526. /**
  1527. * @brief Construct and send a WebSocket frame
  1528. * @param[in] req Current request
  1529. * @param[in] pkt WebSocket frame
  1530. * @return
  1531. * - ESP_OK : On successful
  1532. * - ESP_FAIL : When socket errors occurs
  1533. * - ESP_ERR_INVALID_STATE : Handshake was already done beforehand
  1534. * - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket)
  1535. */
  1536. esp_err_t httpd_ws_send_frame(httpd_req_t *req, httpd_ws_frame_t *pkt);
  1537. /**
  1538. * @brief Low level send of a WebSocket frame out of the scope of current request
  1539. * using internally configured httpd send function
  1540. *
  1541. * This API should rarely be called directly, with an exception of asynchronous send using httpd_queue_work.
  1542. *
  1543. * @param[in] hd Server instance data
  1544. * @param[in] fd Socket descriptor for sending data
  1545. * @param[in] frame WebSocket frame
  1546. * @return
  1547. * - ESP_OK : On successful
  1548. * - ESP_FAIL : When socket errors occurs
  1549. * - ESP_ERR_INVALID_STATE : Handshake was already done beforehand
  1550. * - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket)
  1551. */
  1552. esp_err_t httpd_ws_send_frame_async(httpd_handle_t hd, int fd, httpd_ws_frame_t *frame);
  1553. /**
  1554. * @brief Checks the supplied socket descriptor if it belongs to any active client
  1555. * of this server instance and if the websoket protocol is active
  1556. *
  1557. * @param[in] hd Server instance data
  1558. * @param[in] fd Socket descriptor
  1559. * @return
  1560. * - HTTPD_WS_CLIENT_INVALID : This fd is not a client of this httpd
  1561. * - HTTPD_WS_CLIENT_HTTP : This fd is an active client, protocol is not WS
  1562. * - HTTPD_WS_CLIENT_WEBSOCKET : This fd is an active client, protocol is WS
  1563. */
  1564. httpd_ws_client_info_t httpd_ws_get_fd_info(httpd_handle_t hd, int fd);
  1565. /**
  1566. * @brief Sends data to to specified websocket synchronously
  1567. *
  1568. * @param[in] handle Server instance data
  1569. * @param[in] socket Socket descriptor
  1570. * @param[in] frame Websocket frame
  1571. * @return
  1572. * - ESP_OK : On successful
  1573. * - ESP_FAIL : When socket errors occurs
  1574. * - ESP_ERR_NO_MEM : Unable to allocate memory
  1575. */
  1576. esp_err_t httpd_ws_send_data(httpd_handle_t handle, int socket, httpd_ws_frame_t *frame);
  1577. /**
  1578. * @brief Sends data to to specified websocket asynchronously
  1579. *
  1580. * @param[in] handle Server instance data
  1581. * @param[in] socket Socket descriptor
  1582. * @param[in] frame Websocket frame
  1583. * @param[in] callback Callback invoked after sending data
  1584. * @param[in] arg User data passed to provided callback
  1585. * @return
  1586. * - ESP_OK : On successful
  1587. * - ESP_FAIL : When socket errors occurs
  1588. * - ESP_ERR_NO_MEM : Unable to allocate memory
  1589. */
  1590. esp_err_t httpd_ws_send_data_async(httpd_handle_t handle, int socket, httpd_ws_frame_t *frame,
  1591. transfer_complete_cb callback, void *arg);
  1592. #endif /* CONFIG_HTTPD_WS_SUPPORT */
  1593. /** End of WebSocket related stuff
  1594. * @}
  1595. */
  1596. #ifdef __cplusplus
  1597. }
  1598. #endif
  1599. #endif /* ! _ESP_HTTP_SERVER_H_ */