esp_http_server.h 68 KB

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