esp_http_server.h 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785
  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 Start an asynchronous request. This function can be called
  740. * in a request handler to get a request copy that can be used on a async thread.
  741. *
  742. * @note
  743. * - This function is necessary in order to handle multiple requests simultaneously.
  744. * See examples/async_requests for example usage.
  745. * - You must call httpd_req_async_handler_complete() when you are done with the request.
  746. *
  747. * @param[in] r The request to create an async copy of
  748. * @param[out] out A newly allocated request which can be used on an async thread
  749. *
  750. * @return
  751. * - ESP_OK : async request object created
  752. */
  753. esp_err_t httpd_req_async_handler_begin(httpd_req_t *r, httpd_req_t **out);
  754. /**
  755. * @brief Mark an asynchronous request as completed. This will
  756. * - free the request memory
  757. * - relinquish ownership of the underlying socket, so it can be reused.
  758. * - allow the http server to close our socket if needed (lru_purge_enable)
  759. *
  760. * @note If async requests are not marked completed, eventually the server
  761. * will no longer accept incoming connections. The server will log a
  762. * "httpd_accept_conn: error in accept (23)" message if this happens.
  763. *
  764. * @param[in] r The request to mark async work as completed
  765. *
  766. * @return
  767. * - ESP_OK : async request was marked completed
  768. */
  769. esp_err_t httpd_req_async_handler_complete(httpd_req_t *r);
  770. /**
  771. * @brief Get the Socket Descriptor from the HTTP request
  772. *
  773. * This API will return the socket descriptor of the session for
  774. * which URI handler was executed on reception of HTTP request.
  775. * This is useful when user wants to call functions that require
  776. * session socket fd, from within a URI handler, ie. :
  777. * httpd_sess_get_ctx(),
  778. * httpd_sess_trigger_close(),
  779. * httpd_sess_update_lru_counter().
  780. *
  781. * @note This API is supposed to be called only from the context of
  782. * a URI handler where httpd_req_t* request pointer is valid.
  783. *
  784. * @param[in] r The request whose socket descriptor should be found
  785. *
  786. * @return
  787. * - Socket descriptor : The socket descriptor for this request
  788. * - -1 : Invalid/NULL request pointer
  789. */
  790. int httpd_req_to_sockfd(httpd_req_t *r);
  791. /**
  792. * @brief API to read content data from the HTTP request
  793. *
  794. * This API will read HTTP content data from the HTTP request into
  795. * provided buffer. Use content_len provided in httpd_req_t structure
  796. * to know the length of data to be fetched. If content_len is too
  797. * large for the buffer then user may have to make multiple calls to
  798. * this function, each time fetching 'buf_len' number of bytes,
  799. * while the pointer to content data is incremented internally by
  800. * the same number.
  801. *
  802. * @note
  803. * - This API is supposed to be called only from the context of
  804. * a URI handler where httpd_req_t* request pointer is valid.
  805. * - If an error is returned, the URI handler must further return an error.
  806. * This will ensure that the erroneous socket is closed and cleaned up by
  807. * the web server.
  808. * - Presently Chunked Encoding is not supported
  809. *
  810. * @param[in] r The request being responded to
  811. * @param[in] buf Pointer to a buffer that the data will be read into
  812. * @param[in] buf_len Length of the buffer
  813. *
  814. * @return
  815. * - Bytes : Number of bytes read into the buffer successfully
  816. * - 0 : Buffer length parameter is zero / connection closed by peer
  817. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  818. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
  819. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
  820. */
  821. int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len);
  822. /**
  823. * @brief Search for a field in request headers and
  824. * return the string length of it's value
  825. *
  826. * @note
  827. * - This API is supposed to be called only from the context of
  828. * a URI handler where httpd_req_t* request pointer is valid.
  829. * - Once httpd_resp_send() API is called all request headers
  830. * are purged, so request headers need be copied into separate
  831. * buffers if they are required later.
  832. *
  833. * @param[in] r The request being responded to
  834. * @param[in] field The header field to be searched in the request
  835. *
  836. * @return
  837. * - Length : If field is found in the request URL
  838. * - Zero : Field not found / Invalid request / Null arguments
  839. */
  840. size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field);
  841. /**
  842. * @brief Get the value string of a field from the request headers
  843. *
  844. * @note
  845. * - This API is supposed to be called only from the context of
  846. * a URI handler where httpd_req_t* request pointer is valid.
  847. * - Once httpd_resp_send() API is called all request headers
  848. * are purged, so request headers need be copied into separate
  849. * buffers if they are required later.
  850. * - If output size is greater than input, then the value is truncated,
  851. * accompanied by truncation error as return value.
  852. * - Use httpd_req_get_hdr_value_len() to know the right buffer length
  853. *
  854. * @param[in] r The request being responded to
  855. * @param[in] field The field to be searched in the header
  856. * @param[out] val Pointer to the buffer into which the value will be copied if the field is found
  857. * @param[in] val_size Size of the user buffer "val"
  858. *
  859. * @return
  860. * - ESP_OK : Field found in the request header and value string copied
  861. * - ESP_ERR_NOT_FOUND : Key not found
  862. * - ESP_ERR_INVALID_ARG : Null arguments
  863. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  864. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  865. */
  866. esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size);
  867. /**
  868. * @brief Get Query string length from the request URL
  869. *
  870. * @note This API is supposed to be called only from the context of
  871. * a URI handler where httpd_req_t* request pointer is valid
  872. *
  873. * @param[in] r The request being responded to
  874. *
  875. * @return
  876. * - Length : Query is found in the request URL
  877. * - Zero : Query not found / Null arguments / Invalid request
  878. */
  879. size_t httpd_req_get_url_query_len(httpd_req_t *r);
  880. /**
  881. * @brief Get Query string from the request URL
  882. *
  883. * @note
  884. * - Presently, the user can fetch the full URL query string, but decoding
  885. * will have to be performed by the user. Request headers can be read using
  886. * httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type:
  887. * application/x-www-form-urlencoded) and then the appropriate decoding
  888. * algorithm needs to be applied.
  889. * - This API is supposed to be called only from the context of
  890. * a URI handler where httpd_req_t* request pointer is valid
  891. * - If output size is greater than input, then the value is truncated,
  892. * accompanied by truncation error as return value
  893. * - Prior to calling this function, one can use httpd_req_get_url_query_len()
  894. * to know the query string length beforehand and hence allocate the buffer
  895. * of right size (usually query string length + 1 for null termination)
  896. * for storing the query string
  897. *
  898. * @param[in] r The request being responded to
  899. * @param[out] buf Pointer to the buffer into which the query string will be copied (if found)
  900. * @param[in] buf_len Length of output buffer
  901. *
  902. * @return
  903. * - ESP_OK : Query is found in the request URL and copied to buffer
  904. * - ESP_ERR_NOT_FOUND : Query not found
  905. * - ESP_ERR_INVALID_ARG : Null arguments
  906. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
  907. * - ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated
  908. */
  909. esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len);
  910. /**
  911. * @brief Helper function to get a URL query tag from a query
  912. * string of the type param1=val1&param2=val2
  913. *
  914. * @note
  915. * - The components of URL query string (keys and values) are not URLdecoded.
  916. * The user must check for 'Content-Type' field in the request headers and
  917. * then depending upon the specified encoding (URLencoded or otherwise) apply
  918. * the appropriate decoding algorithm.
  919. * - If actual value size is greater than val_size, then the value is truncated,
  920. * accompanied by truncation error as return value.
  921. *
  922. * @param[in] qry Pointer to query string
  923. * @param[in] key The key to be searched in the query string
  924. * @param[out] val Pointer to the buffer into which the value will be copied if the key is found
  925. * @param[in] val_size Size of the user buffer "val"
  926. *
  927. * @return
  928. * - ESP_OK : Key is found in the URL query string and copied to buffer
  929. * - ESP_ERR_NOT_FOUND : Key not found
  930. * - ESP_ERR_INVALID_ARG : Null arguments
  931. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  932. */
  933. esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size);
  934. /**
  935. * @brief Get the value string of a cookie value from the "Cookie" request headers by cookie name.
  936. *
  937. * @param[in] req Pointer to the HTTP request
  938. * @param[in] cookie_name The cookie name to be searched in the request
  939. * @param[out] val Pointer to the buffer into which the value of cookie will be copied if the cookie is found
  940. * @param[inout] val_size Pointer to size of the user buffer "val". This variable will contain cookie length if
  941. * ESP_OK is returned and required buffer length incase ESP_ERR_HTTPD_RESULT_TRUNC is returned.
  942. *
  943. * @return
  944. * - ESP_OK : Key is found in the cookie string and copied to buffer
  945. * - ESP_ERR_NOT_FOUND : Key not found
  946. * - ESP_ERR_INVALID_ARG : Null arguments
  947. * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
  948. * - ESP_ERR_NO_MEM : Memory allocation failure
  949. */
  950. esp_err_t httpd_req_get_cookie_val(httpd_req_t *req, const char *cookie_name, char *val, size_t *val_size);
  951. /**
  952. * @brief Test if a URI matches the given wildcard template.
  953. *
  954. * Template may end with "?" to make the previous character optional (typically a slash),
  955. * "*" for a wildcard match, and "?*" to make the previous character optional, and if present,
  956. * allow anything to follow.
  957. *
  958. * Example:
  959. * - * matches everything
  960. * - /foo/? matches /foo and /foo/
  961. * - /foo/\* (sans the backslash) matches /foo/ and /foo/bar, but not /foo or /fo
  962. * - /foo/?* or /foo/\*? (sans the backslash) matches /foo/, /foo/bar, and also /foo, but not /foox or /fo
  963. *
  964. * The special characters "?" and "*" anywhere else in the template will be taken literally.
  965. *
  966. * @param[in] uri_template URI template (pattern)
  967. * @param[in] uri_to_match URI to be matched
  968. * @param[in] match_upto how many characters of the URI buffer to test
  969. * (there may be trailing query string etc.)
  970. *
  971. * @return true if a match was found
  972. */
  973. bool httpd_uri_match_wildcard(const char *uri_template, const char *uri_to_match, size_t match_upto);
  974. /**
  975. * @brief API to send a complete HTTP response.
  976. *
  977. * This API will send the data as an HTTP response to the request.
  978. * This assumes that you have the entire response ready in a single
  979. * buffer. If you wish to send response in incremental chunks use
  980. * httpd_resp_send_chunk() instead.
  981. *
  982. * If no status code and content-type were set, by default this
  983. * will send 200 OK status code and content type as text/html.
  984. * You may call the following functions before this API to configure
  985. * the response headers :
  986. * httpd_resp_set_status() - for setting the HTTP status string,
  987. * httpd_resp_set_type() - for setting the Content Type,
  988. * httpd_resp_set_hdr() - for appending any additional field
  989. * value entries in the response header
  990. *
  991. * @note
  992. * - This API is supposed to be called only from the context of
  993. * a URI handler where httpd_req_t* request pointer is valid.
  994. * - Once this API is called, the request has been responded to.
  995. * - No additional data can then be sent for the request.
  996. * - Once this API is called, all request headers are purged, so
  997. * request headers need be copied into separate buffers if
  998. * they are required later.
  999. *
  1000. * @param[in] r The request being responded to
  1001. * @param[in] buf Buffer from where the content is to be fetched
  1002. * @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
  1003. *
  1004. * @return
  1005. * - ESP_OK : On successfully sending the response packet
  1006. * - ESP_ERR_INVALID_ARG : Null request pointer
  1007. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  1008. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1009. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  1010. */
  1011. esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len);
  1012. /**
  1013. * @brief API to send one HTTP chunk
  1014. *
  1015. * This API will send the data as an HTTP response to the
  1016. * request. This API will use chunked-encoding and send the response
  1017. * in the form of chunks. If you have the entire response contained in
  1018. * a single buffer, please use httpd_resp_send() instead.
  1019. *
  1020. * If no status code and content-type were set, by default this will
  1021. * send 200 OK status code and content type as text/html. You may
  1022. * call the following functions before this API to configure the
  1023. * response headers
  1024. * httpd_resp_set_status() - for setting the HTTP status string,
  1025. * httpd_resp_set_type() - for setting the Content Type,
  1026. * httpd_resp_set_hdr() - for appending any additional field
  1027. * value entries in the response header
  1028. *
  1029. * @note
  1030. * - This API is supposed to be called only from the context of
  1031. * a URI handler where httpd_req_t* request pointer is valid.
  1032. * - When you are finished sending all your chunks, you must call
  1033. * this function with buf_len as 0.
  1034. * - Once this API is called, all request headers are purged, so
  1035. * request headers need be copied into separate buffers if they
  1036. * are required later.
  1037. *
  1038. * @param[in] r The request being responded to
  1039. * @param[in] buf Pointer to a buffer that stores the data
  1040. * @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
  1041. *
  1042. * @return
  1043. * - ESP_OK : On successfully sending the response packet chunk
  1044. * - ESP_ERR_INVALID_ARG : Null request pointer
  1045. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  1046. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1047. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1048. */
  1049. esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, ssize_t buf_len);
  1050. /**
  1051. * @brief API to send a complete string as HTTP response.
  1052. *
  1053. * This API simply calls http_resp_send with buffer length
  1054. * set to string length assuming the buffer contains a null
  1055. * terminated string
  1056. *
  1057. * @param[in] r The request being responded to
  1058. * @param[in] str String to be sent as response body
  1059. *
  1060. * @return
  1061. * - ESP_OK : On successfully sending the response packet
  1062. * - ESP_ERR_INVALID_ARG : Null request pointer
  1063. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  1064. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1065. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  1066. */
  1067. static inline esp_err_t httpd_resp_sendstr(httpd_req_t *r, const char *str) {
  1068. return httpd_resp_send(r, str, (str == NULL) ? 0 : HTTPD_RESP_USE_STRLEN);
  1069. }
  1070. /**
  1071. * @brief API to send a string as an HTTP response chunk.
  1072. *
  1073. * This API simply calls http_resp_send_chunk with buffer length
  1074. * set to string length assuming the buffer contains a null
  1075. * terminated string
  1076. *
  1077. * @param[in] r The request being responded to
  1078. * @param[in] str String to be sent as response body (NULL to finish response packet)
  1079. *
  1080. * @return
  1081. * - ESP_OK : On successfully sending the response packet
  1082. * - ESP_ERR_INVALID_ARG : Null request pointer
  1083. * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
  1084. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1085. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
  1086. */
  1087. static inline esp_err_t httpd_resp_sendstr_chunk(httpd_req_t *r, const char *str) {
  1088. return httpd_resp_send_chunk(r, str, (str == NULL) ? 0 : HTTPD_RESP_USE_STRLEN);
  1089. }
  1090. /* Some commonly used status codes */
  1091. #define HTTPD_200 "200 OK" /*!< HTTP Response 200 */
  1092. #define HTTPD_204 "204 No Content" /*!< HTTP Response 204 */
  1093. #define HTTPD_207 "207 Multi-Status" /*!< HTTP Response 207 */
  1094. #define HTTPD_400 "400 Bad Request" /*!< HTTP Response 400 */
  1095. #define HTTPD_404 "404 Not Found" /*!< HTTP Response 404 */
  1096. #define HTTPD_408 "408 Request Timeout" /*!< HTTP Response 408 */
  1097. #define HTTPD_500 "500 Internal Server Error" /*!< HTTP Response 500 */
  1098. /**
  1099. * @brief API to set the HTTP status code
  1100. *
  1101. * This API sets the status of the HTTP response to the value specified.
  1102. * By default, the '200 OK' response is sent as the response.
  1103. *
  1104. * @note
  1105. * - This API is supposed to be called only from the context of
  1106. * a URI handler where httpd_req_t* request pointer is valid.
  1107. * - This API only sets the status to this value. The status isn't
  1108. * sent out until any of the send APIs is executed.
  1109. * - Make sure that the lifetime of the status string is valid till
  1110. * send function is called.
  1111. *
  1112. * @param[in] r The request being responded to
  1113. * @param[in] status The HTTP status code of this response
  1114. *
  1115. * @return
  1116. * - ESP_OK : On success
  1117. * - ESP_ERR_INVALID_ARG : Null arguments
  1118. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1119. */
  1120. esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status);
  1121. /* Some commonly used content types */
  1122. #define HTTPD_TYPE_JSON "application/json" /*!< HTTP Content type JSON */
  1123. #define HTTPD_TYPE_TEXT "text/html" /*!< HTTP Content type text/HTML */
  1124. #define HTTPD_TYPE_OCTET "application/octet-stream" /*!< HTTP Content type octext-stream */
  1125. /**
  1126. * @brief API to set the HTTP content type
  1127. *
  1128. * This API sets the 'Content Type' field of the response.
  1129. * The default content type is 'text/html'.
  1130. *
  1131. * @note
  1132. * - This API is supposed to be called only from the context of
  1133. * a URI handler where httpd_req_t* request pointer is valid.
  1134. * - This API only sets the content type to this value. The type
  1135. * isn't sent out until any of the send APIs is executed.
  1136. * - Make sure that the lifetime of the type string is valid till
  1137. * send function is called.
  1138. *
  1139. * @param[in] r The request being responded to
  1140. * @param[in] type The Content Type of the response
  1141. *
  1142. * @return
  1143. * - ESP_OK : On success
  1144. * - ESP_ERR_INVALID_ARG : Null arguments
  1145. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1146. */
  1147. esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type);
  1148. /**
  1149. * @brief API to append any additional headers
  1150. *
  1151. * This API sets any additional header fields that need to be sent in the response.
  1152. *
  1153. * @note
  1154. * - This API is supposed to be called only from the context of
  1155. * a URI handler where httpd_req_t* request pointer is valid.
  1156. * - The header isn't sent out until any of the send APIs is executed.
  1157. * - The maximum allowed number of additional headers is limited to
  1158. * value of max_resp_headers in config structure.
  1159. * - Make sure that the lifetime of the field value strings are valid till
  1160. * send function is called.
  1161. *
  1162. * @param[in] r The request being responded to
  1163. * @param[in] field The field name of the HTTP header
  1164. * @param[in] value The value of this HTTP header
  1165. *
  1166. * @return
  1167. * - ESP_OK : On successfully appending new header
  1168. * - ESP_ERR_INVALID_ARG : Null arguments
  1169. * - ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed
  1170. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1171. */
  1172. esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value);
  1173. /**
  1174. * @brief For sending out error code in response to HTTP request.
  1175. *
  1176. * @note
  1177. * - This API is supposed to be called only from the context of
  1178. * a URI handler where httpd_req_t* request pointer is valid.
  1179. * - Once this API is called, all request headers are purged, so
  1180. * request headers need be copied into separate buffers if
  1181. * they are required later.
  1182. * - If you wish to send additional data in the body of the
  1183. * response, please use the lower-level functions directly.
  1184. *
  1185. * @param[in] req Pointer to the HTTP request for which the response needs to be sent
  1186. * @param[in] error Error type to send
  1187. * @param[in] msg Error message string (pass NULL for default message)
  1188. *
  1189. * @return
  1190. * - ESP_OK : On successfully sending the response packet
  1191. * - ESP_ERR_INVALID_ARG : Null arguments
  1192. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1193. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1194. */
  1195. esp_err_t httpd_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *msg);
  1196. /**
  1197. * @brief Helper function for HTTP 404
  1198. *
  1199. * Send HTTP 404 message. If you wish to send additional data in the body of the
  1200. * response, please use the lower-level functions directly.
  1201. *
  1202. * @note
  1203. * - This API is supposed to be called only from the context of
  1204. * a URI handler where httpd_req_t* request pointer is valid.
  1205. * - Once this API is called, all request headers are purged, so
  1206. * request headers need be copied into separate buffers if
  1207. * they are required later.
  1208. *
  1209. * @param[in] r The request being responded to
  1210. *
  1211. * @return
  1212. * - ESP_OK : On successfully sending the response packet
  1213. * - ESP_ERR_INVALID_ARG : Null arguments
  1214. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1215. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1216. */
  1217. static inline esp_err_t httpd_resp_send_404(httpd_req_t *r) {
  1218. return httpd_resp_send_err(r, HTTPD_404_NOT_FOUND, NULL);
  1219. }
  1220. /**
  1221. * @brief Helper function for HTTP 408
  1222. *
  1223. * Send HTTP 408 message. If you wish to send additional data in the body of the
  1224. * response, please use the lower-level functions directly.
  1225. *
  1226. * @note
  1227. * - This API is supposed to be called only from the context of
  1228. * a URI handler where httpd_req_t* request pointer is valid.
  1229. * - Once this API is called, all request headers are purged, so
  1230. * request headers need be copied into separate buffers if
  1231. * they are required later.
  1232. *
  1233. * @param[in] r The request being responded to
  1234. *
  1235. * @return
  1236. * - ESP_OK : On successfully sending the response packet
  1237. * - ESP_ERR_INVALID_ARG : Null arguments
  1238. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1239. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1240. */
  1241. static inline esp_err_t httpd_resp_send_408(httpd_req_t *r) {
  1242. return httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT, NULL);
  1243. }
  1244. /**
  1245. * @brief Helper function for HTTP 500
  1246. *
  1247. * Send HTTP 500 message. If you wish to send additional data in the body of the
  1248. * response, please use the lower-level functions directly.
  1249. *
  1250. * @note
  1251. * - This API is supposed to be called only from the context of
  1252. * a URI handler where httpd_req_t* request pointer is valid.
  1253. * - Once this API is called, all request headers are purged, so
  1254. * request headers need be copied into separate buffers if
  1255. * they are required later.
  1256. *
  1257. * @param[in] r The request being responded to
  1258. *
  1259. * @return
  1260. * - ESP_OK : On successfully sending the response packet
  1261. * - ESP_ERR_INVALID_ARG : Null arguments
  1262. * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
  1263. * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
  1264. */
  1265. static inline esp_err_t httpd_resp_send_500(httpd_req_t *r) {
  1266. return httpd_resp_send_err(r, HTTPD_500_INTERNAL_SERVER_ERROR, NULL);
  1267. }
  1268. /**
  1269. * @brief Raw HTTP send
  1270. *
  1271. * Call this API if you wish to construct your custom response packet.
  1272. * When using this, all essential header, eg. HTTP version, Status Code,
  1273. * Content Type and Length, Encoding, etc. will have to be constructed
  1274. * manually, and HTTP delimeters (CRLF) will need to be placed correctly
  1275. * for separating sub-sections of the HTTP response packet.
  1276. *
  1277. * If the send override function is set, this API will end up
  1278. * calling that function eventually to send data out.
  1279. *
  1280. * @note
  1281. * - This API is supposed to be called only from the context of
  1282. * a URI handler where httpd_req_t* request pointer is valid.
  1283. * - Unless the response has the correct HTTP structure (which the
  1284. * user must now ensure) it is not guaranteed that it will be
  1285. * recognized by the client. For most cases, you wouldn't have
  1286. * to call this API, but you would rather use either of :
  1287. * httpd_resp_send(),
  1288. * httpd_resp_send_chunk()
  1289. *
  1290. * @param[in] r The request being responded to
  1291. * @param[in] buf Buffer from where the fully constructed packet is to be read
  1292. * @param[in] buf_len Length of the buffer
  1293. *
  1294. * @return
  1295. * - Bytes : Number of bytes that were sent successfully
  1296. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  1297. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
  1298. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
  1299. */
  1300. int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len);
  1301. /**
  1302. * A low level API to send data on a given socket
  1303. *
  1304. * @note This API is not recommended to be used in any request handler.
  1305. * Use this only for advanced use cases, wherein some asynchronous
  1306. * data is to be sent over a socket.
  1307. *
  1308. * This internally calls the default send function, or the function registered by
  1309. * httpd_sess_set_send_override().
  1310. *
  1311. * @param[in] hd server instance
  1312. * @param[in] sockfd session socket file descriptor
  1313. * @param[in] buf buffer with bytes to send
  1314. * @param[in] buf_len data size
  1315. * @param[in] flags flags for the send() function
  1316. * @return
  1317. * - Bytes : The number of bytes sent successfully
  1318. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  1319. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
  1320. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
  1321. */
  1322. int httpd_socket_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags);
  1323. /**
  1324. * A low level API to receive data from a given socket
  1325. *
  1326. * @note This API is not recommended to be used in any request handler.
  1327. * Use this only for advanced use cases, wherein some asynchronous
  1328. * communication is required.
  1329. *
  1330. * This internally calls the default recv function, or the function registered by
  1331. * httpd_sess_set_recv_override().
  1332. *
  1333. * @param[in] hd server instance
  1334. * @param[in] sockfd session socket file descriptor
  1335. * @param[in] buf buffer with bytes to send
  1336. * @param[in] buf_len data size
  1337. * @param[in] flags flags for the send() function
  1338. * @return
  1339. * - Bytes : The number of bytes received successfully
  1340. * - 0 : Buffer length parameter is zero / connection closed by peer
  1341. * - HTTPD_SOCK_ERR_INVALID : Invalid arguments
  1342. * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
  1343. * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
  1344. */
  1345. int httpd_socket_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags);
  1346. /** End of Request / Response
  1347. * @}
  1348. */
  1349. /* ************** Group: Session ************** */
  1350. /** @name Session
  1351. * Functions for controlling sessions and accessing context data
  1352. * @{
  1353. */
  1354. /**
  1355. * @brief Get session context from socket descriptor
  1356. *
  1357. * Typically if a session context is created, it is available to URI handlers
  1358. * through the httpd_req_t structure. But, there are cases where the web
  1359. * server's send/receive functions may require the context (for example, for
  1360. * accessing keying information etc). Since the send/receive function only have
  1361. * the socket descriptor at their disposal, this API provides them with a way to
  1362. * retrieve the session context.
  1363. *
  1364. * @param[in] handle Handle to server returned by httpd_start
  1365. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1366. *
  1367. * @return
  1368. * - void* : Pointer to the context associated with this session
  1369. * - NULL : Empty context / Invalid handle / Invalid socket fd
  1370. */
  1371. void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd);
  1372. /**
  1373. * @brief Set session context by socket descriptor
  1374. *
  1375. * @param[in] handle Handle to server returned by httpd_start
  1376. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1377. * @param[in] ctx Context object to assign to the session
  1378. * @param[in] free_fn Function that should be called to free the context
  1379. */
  1380. void httpd_sess_set_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn);
  1381. /**
  1382. * @brief Get session 'transport' context by socket descriptor
  1383. * @see httpd_sess_get_ctx()
  1384. *
  1385. * This context is used by the send/receive functions, for example to manage SSL context.
  1386. *
  1387. * @param[in] handle Handle to server returned by httpd_start
  1388. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1389. * @return
  1390. * - void* : Pointer to the transport context associated with this session
  1391. * - NULL : Empty context / Invalid handle / Invalid socket fd
  1392. */
  1393. void *httpd_sess_get_transport_ctx(httpd_handle_t handle, int sockfd);
  1394. /**
  1395. * @brief Set session 'transport' context by socket descriptor
  1396. * @see httpd_sess_set_ctx()
  1397. *
  1398. * @param[in] handle Handle to server returned by httpd_start
  1399. * @param[in] sockfd The socket descriptor for which the context should be extracted.
  1400. * @param[in] ctx Transport context object to assign to the session
  1401. * @param[in] free_fn Function that should be called to free the transport context
  1402. */
  1403. void httpd_sess_set_transport_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn);
  1404. /**
  1405. * @brief Get HTTPD global user context (it was set in the server config struct)
  1406. *
  1407. * @param[in] handle Handle to server returned by httpd_start
  1408. * @return global user context
  1409. */
  1410. void *httpd_get_global_user_ctx(httpd_handle_t handle);
  1411. /**
  1412. * @brief Get HTTPD global transport context (it was set in the server config struct)
  1413. *
  1414. * @param[in] handle Handle to server returned by httpd_start
  1415. * @return global transport context
  1416. */
  1417. void *httpd_get_global_transport_ctx(httpd_handle_t handle);
  1418. /**
  1419. * @brief Trigger an httpd session close externally
  1420. *
  1421. * @note Calling this API is only required in special circumstances wherein
  1422. * some application requires to close an httpd client session asynchronously.
  1423. *
  1424. * @param[in] handle Handle to server returned by httpd_start
  1425. * @param[in] sockfd The socket descriptor of the session to be closed
  1426. *
  1427. * @return
  1428. * - ESP_OK : On successfully initiating closure
  1429. * - ESP_FAIL : Failure to queue work
  1430. * - ESP_ERR_NOT_FOUND : Socket fd not found
  1431. * - ESP_ERR_INVALID_ARG : Null arguments
  1432. */
  1433. esp_err_t httpd_sess_trigger_close(httpd_handle_t handle, int sockfd);
  1434. /**
  1435. * @brief Update LRU counter for a given socket
  1436. *
  1437. * LRU Counters are internally associated with each session to monitor
  1438. * how recently a session exchanged traffic. When LRU purge is enabled,
  1439. * if a client is requesting for connection but maximum number of
  1440. * sockets/sessions is reached, then the session having the earliest
  1441. * LRU counter is closed automatically.
  1442. *
  1443. * Updating the LRU counter manually prevents the socket from being purged
  1444. * due to the Least Recently Used (LRU) logic, even though it might not
  1445. * have received traffic for some time. This is useful when all open
  1446. * sockets/session are frequently exchanging traffic but the user specifically
  1447. * wants one of the sessions to be kept open, irrespective of when it last
  1448. * exchanged a packet.
  1449. *
  1450. * @note Calling this API is only necessary if the LRU Purge Enable option
  1451. * is enabled.
  1452. *
  1453. * @param[in] handle Handle to server returned by httpd_start
  1454. * @param[in] sockfd The socket descriptor of the session for which LRU counter
  1455. * is to be updated
  1456. *
  1457. * @return
  1458. * - ESP_OK : Socket found and LRU counter updated
  1459. * - ESP_ERR_NOT_FOUND : Socket not found
  1460. * - ESP_ERR_INVALID_ARG : Null arguments
  1461. */
  1462. esp_err_t httpd_sess_update_lru_counter(httpd_handle_t handle, int sockfd);
  1463. /**
  1464. * @brief Returns list of current socket descriptors of active sessions
  1465. *
  1466. * @param[in] handle Handle to server returned by httpd_start
  1467. * @param[in,out] fds In: Size of provided client_fds array
  1468. * Out: Number of valid client fds returned in client_fds,
  1469. * @param[out] client_fds Array of client fds
  1470. *
  1471. * @note Size of provided array has to be equal or greater then maximum number of opened
  1472. * sockets, configured upon initialization with max_open_sockets field in
  1473. * httpd_config_t structure.
  1474. *
  1475. * @return
  1476. * - ESP_OK : Successfully retrieved session list
  1477. * - ESP_ERR_INVALID_ARG : Wrong arguments or list is longer than provided array
  1478. */
  1479. esp_err_t httpd_get_client_list(httpd_handle_t handle, size_t *fds, int *client_fds);
  1480. /** End of Session
  1481. * @}
  1482. */
  1483. /* ************** Group: Work Queue ************** */
  1484. /** @name Work Queue
  1485. * APIs related to the HTTPD Work Queue
  1486. * @{
  1487. */
  1488. /**
  1489. * @brief Prototype of the HTTPD work function
  1490. * Please refer to httpd_queue_work() for more details.
  1491. * @param[in] arg The arguments for this work function
  1492. */
  1493. typedef void (*httpd_work_fn_t)(void *arg);
  1494. /**
  1495. * @brief Queue execution of a function in HTTPD's context
  1496. *
  1497. * This API queues a work function for asynchronous execution
  1498. *
  1499. * @note Some protocols require that the web server generate some asynchronous data
  1500. * and send it to the persistently opened connection. This facility is for use
  1501. * by such protocols.
  1502. *
  1503. * @param[in] handle Handle to server returned by httpd_start
  1504. * @param[in] work Pointer to the function to be executed in the HTTPD's context
  1505. * @param[in] arg Pointer to the arguments that should be passed to this function
  1506. *
  1507. * @return
  1508. * - ESP_OK : On successfully queueing the work
  1509. * - ESP_FAIL : Failure in ctrl socket
  1510. * - ESP_ERR_INVALID_ARG : Null arguments
  1511. */
  1512. esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg);
  1513. /** End of Group Work Queue
  1514. * @}
  1515. */
  1516. /* ************** Group: WebSocket ************** */
  1517. /** @name WebSocket
  1518. * Functions and structs for WebSocket server
  1519. * @{
  1520. */
  1521. #ifdef CONFIG_HTTPD_WS_SUPPORT
  1522. /**
  1523. * @brief Enum for WebSocket packet types (Opcode in the header)
  1524. * @note Please refer to RFC6455 Section 5.4 for more details
  1525. */
  1526. typedef enum {
  1527. HTTPD_WS_TYPE_CONTINUE = 0x0,
  1528. HTTPD_WS_TYPE_TEXT = 0x1,
  1529. HTTPD_WS_TYPE_BINARY = 0x2,
  1530. HTTPD_WS_TYPE_CLOSE = 0x8,
  1531. HTTPD_WS_TYPE_PING = 0x9,
  1532. HTTPD_WS_TYPE_PONG = 0xA
  1533. } httpd_ws_type_t;
  1534. /**
  1535. * @brief Enum for client info description
  1536. */
  1537. typedef enum {
  1538. HTTPD_WS_CLIENT_INVALID = 0x0,
  1539. HTTPD_WS_CLIENT_HTTP = 0x1,
  1540. HTTPD_WS_CLIENT_WEBSOCKET = 0x2,
  1541. } httpd_ws_client_info_t;
  1542. /**
  1543. * @brief WebSocket frame format
  1544. */
  1545. typedef struct httpd_ws_frame {
  1546. bool final; /*!< Final frame:
  1547. For received frames this field indicates whether the `FIN` flag was set.
  1548. For frames to be transmitted, this field is only used if the `fragmented`
  1549. option is set as well. If `fragmented` is false, the `FIN` flag is set
  1550. by default, marking the ws_frame as a complete/unfragmented message
  1551. (esp_http_server doesn't automatically fragment messages) */
  1552. bool fragmented; /*!< Indication that the frame allocated for transmission is a message fragment,
  1553. so the `FIN` flag is set manually according to the `final` option.
  1554. This flag is never set for received messages */
  1555. httpd_ws_type_t type; /*!< WebSocket frame type */
  1556. uint8_t *payload; /*!< Pre-allocated data buffer */
  1557. size_t len; /*!< Length of the WebSocket data */
  1558. } httpd_ws_frame_t;
  1559. /**
  1560. * @brief Transfer complete callback
  1561. */
  1562. typedef void (*transfer_complete_cb)(esp_err_t err, int socket, void *arg);
  1563. /**
  1564. * @brief Receive and parse a WebSocket frame
  1565. *
  1566. * @note Calling httpd_ws_recv_frame() with max_len as 0 will give actual frame size in pkt->len.
  1567. * 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.
  1568. * Please refer to the corresponding example for usage.
  1569. *
  1570. * @param[in] req Current request
  1571. * @param[out] pkt WebSocket packet
  1572. * @param[in] max_len Maximum length for receive
  1573. * @return
  1574. * - ESP_OK : On successful
  1575. * - ESP_FAIL : Socket errors occurs
  1576. * - ESP_ERR_INVALID_STATE : Handshake was already done beforehand
  1577. * - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket)
  1578. */
  1579. esp_err_t httpd_ws_recv_frame(httpd_req_t *req, httpd_ws_frame_t *pkt, size_t max_len);
  1580. /**
  1581. * @brief Construct and send a WebSocket frame
  1582. * @param[in] req Current request
  1583. * @param[in] pkt WebSocket frame
  1584. * @return
  1585. * - ESP_OK : On successful
  1586. * - ESP_FAIL : When socket errors occurs
  1587. * - ESP_ERR_INVALID_STATE : Handshake was already done beforehand
  1588. * - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket)
  1589. */
  1590. esp_err_t httpd_ws_send_frame(httpd_req_t *req, httpd_ws_frame_t *pkt);
  1591. /**
  1592. * @brief Low level send of a WebSocket frame out of the scope of current request
  1593. * using internally configured httpd send function
  1594. *
  1595. * This API should rarely be called directly, with an exception of asynchronous send using httpd_queue_work.
  1596. *
  1597. * @param[in] hd Server instance data
  1598. * @param[in] fd Socket descriptor for sending data
  1599. * @param[in] frame WebSocket frame
  1600. * @return
  1601. * - ESP_OK : On successful
  1602. * - ESP_FAIL : When socket errors occurs
  1603. * - ESP_ERR_INVALID_STATE : Handshake was already done beforehand
  1604. * - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket)
  1605. */
  1606. esp_err_t httpd_ws_send_frame_async(httpd_handle_t hd, int fd, httpd_ws_frame_t *frame);
  1607. /**
  1608. * @brief Checks the supplied socket descriptor if it belongs to any active client
  1609. * of this server instance and if the websoket protocol is active
  1610. *
  1611. * @param[in] hd Server instance data
  1612. * @param[in] fd Socket descriptor
  1613. * @return
  1614. * - HTTPD_WS_CLIENT_INVALID : This fd is not a client of this httpd
  1615. * - HTTPD_WS_CLIENT_HTTP : This fd is an active client, protocol is not WS
  1616. * - HTTPD_WS_CLIENT_WEBSOCKET : This fd is an active client, protocol is WS
  1617. */
  1618. httpd_ws_client_info_t httpd_ws_get_fd_info(httpd_handle_t hd, int fd);
  1619. /**
  1620. * @brief Sends data to to specified websocket synchronously
  1621. *
  1622. * @param[in] handle Server instance data
  1623. * @param[in] socket Socket descriptor
  1624. * @param[in] frame Websocket frame
  1625. * @return
  1626. * - ESP_OK : On successful
  1627. * - ESP_FAIL : When socket errors occurs
  1628. * - ESP_ERR_NO_MEM : Unable to allocate memory
  1629. */
  1630. esp_err_t httpd_ws_send_data(httpd_handle_t handle, int socket, httpd_ws_frame_t *frame);
  1631. /**
  1632. * @brief Sends data to to specified websocket asynchronously
  1633. *
  1634. * @param[in] handle Server instance data
  1635. * @param[in] socket Socket descriptor
  1636. * @param[in] frame Websocket frame
  1637. * @param[in] callback Callback invoked after sending data
  1638. * @param[in] arg User data passed to provided callback
  1639. * @return
  1640. * - ESP_OK : On successful
  1641. * - ESP_FAIL : When socket errors occurs
  1642. * - ESP_ERR_NO_MEM : Unable to allocate memory
  1643. */
  1644. esp_err_t httpd_ws_send_data_async(httpd_handle_t handle, int socket, httpd_ws_frame_t *frame,
  1645. transfer_complete_cb callback, void *arg);
  1646. #endif /* CONFIG_HTTPD_WS_SUPPORT */
  1647. /** End of WebSocket related stuff
  1648. * @}
  1649. */
  1650. #ifdef __cplusplus
  1651. }
  1652. #endif
  1653. #endif /* ! _ESP_HTTP_SERVER_H_ */