esp_http_server.h 65 KB

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