esp_http_server.h 66 KB

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