esp_http_server.h 68 KB

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