esp_http_server.h 59 KB

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