esp_http_server.h 66 KB

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