esp_http_server.h 65 KB

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